<commit_before>/*
 * The MIT License
 *
 * Copyright (c) 2012, Jesse Farinacci
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

if (keyboard_shortcuts_enabled) {
  var keyboard_shortcuts_previous_code;
  var keyboard_shortcuts_previous_char;
  var keyboard_shortcuts_view_job_selected;

  Event.observe(window, 'load', function() {
    Event.observe(document, 'keypress', function(e) {

      /* try to play nicely with forms, so no keyboard shortcuts */
      var activeElement = document.activeElement;
      if (activeElement == null || 'INPUT' == activeElement.tagName) {
        return;
      }

      // ---

      var keyboard_shortcuts_code;

      if (!e) {
        e = window.event;
      }

      if (e.keyCode) {
        keyboard_shortcuts_code = e.keyCode;
      }

      else if (e.which) {
        keyboard_shortcuts_code = e.which;
      }

      /* always hide the shortcuts help, if user hits '?' again, re-display it */
      keyboard_shortcuts_hide_keyboard_shortcuts_help();

      var keyboard_shortcuts_character = String.fromCharCode(keyboard_shortcuts_code);

      switch (keyboard_shortcuts_character) {

        case '?':
          keyboard_shortcuts_show_keyboard_shortcuts_help();
          break;

        case '/':
          $('search-box').focus();
          break;

        case 'b':
          if (keyboard_shortcuts_is_job()) {
            window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/build?delay=0sec';
          }
          break;

        case 'c':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/changes';
            }
          }
          break;

        case 'C':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/configure';
            }
          }
          break;

        case 'h':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            window.location.href = keyboard_shortcuts_url;
          }
          break;

        case 'H':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_view()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_view + '/builds';
            }
          }
          break;

        case 'j':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            window.alert('keyboard_shortcuts_app_job_selector');
          }
          else {
            if (keyboard_shortcuts_is_view()) {
              keyboard_shortcuts_view_job_next();
            }
          }
          break;

        case 'k':
          if (keyboard_shortcuts_is_view()) {
            keyboard_shortcuts_view_job_prev();
          }
          break;

        case 'm':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/modules';
            }
            else if (keyboard_shortcuts_is_app()) {
              window.location.href = keyboard_shortcuts_url + '/manage';
            }
          }
          break;

        case 'n':
          if (keyboard_shortcuts_is_view()) {
            keyboard_shortcuts_view_job_next();
          }
          break;

        case 'o':
          if (keyboard_shortcuts_is_view()) {
            keyboard_shortcuts_view_job_open();
          }
          break;

        case 'p':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.alert('keyboard_shortcuts_job_permalink_selector');
            }
            else if (keyboard_shortcuts_is_app()) {
              window.location.href = keyboard_shortcuts_url + '/people';
            }
          }
          else {
            if (keyboard_shortcuts_is_view()) {
              keyboard_shortcuts_view_job_prev();
            }
          }
          break;

        case 'P':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/scmPollLog';
            }
            else if (keyboard_shortcuts_is_app()) {
              window.location.href = keyboard_shortcuts_url + '/pluginManager';
            }
          }
          break;

        case 'r':
          window.location.href = window.location.href;
          break;

        case 's':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job;
            }
          }
          break;

        case 'v':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            window.alert('keyboard_shortcuts_app_view_selector');
          }
          break;

        case 'w':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url_job + '/ws';
            }
          }
          break;

        default:
          console.debug('code: ' + keyboard_shortcuts_code + ', character: ' + keyboard_shortcuts_character);
          break;
      }

      keyboard_shortcuts_previous_code = keyboard_shortcuts_code;
      keyboard_shortcuts_previous_character = String.fromCharCode(keyboard_shortcuts_code);
    });
  });

  function keyboard_shortcuts_is_job() {
    return typeof keyboard_shortcuts_is_job_page != 'undefined' && keyboard_shortcuts_is_job_page;
  }

  function keyboard_shortcuts_is_view() {
    return typeof keyboard_shortcuts_is_view_page != 'undefined' && keyboard_shortcuts_is_view_page;
  }

  function keyboard_shortcuts_show_keyboard_shortcuts_help() {
    $('keyboard-shortcuts-help').show();
  }

  function keyboard_shortcuts_hide_keyboard_shortcuts_help() {
    $('keyboard-shortcuts-help').hide();
  }

  function keyboard_shortcuts_previous_character_was_character(character) {
    if (typeof keyboard_shortcuts_previous_character == 'undefined') {
      return false;
    }

    if (typeof character == 'undefined') {
      return false;
    }

    return keyboard_shortcuts_previous_character == character;
  }

  function keyboard_shortcuts_view_job_next() {
    keyboard_shortcuts_hide_keyboard_shortcuts_help();
    if (typeof keyboard_shortcuts_view_job_names != 'undefined') {
      if (keyboard_shortcuts_view_job_names.length > 0) {
        keyboard_shortcuts_view_job_names.each(function(job) {
          $('job_' + job).removeClassName('keyboard-shortcuts-view-job-selected');
        });
        var idx = keyboard_shortcuts_view_job_names.indexOf(keyboard_shortcuts_view_job_selected) + 1;
        if (idx >= keyboard_shortcuts_view_job_names.length) {
          idx = 0;
        }
        keyboard_shortcuts_view_job_selected = keyboard_shortcuts_view_job_names[idx];
        $('job_' + keyboard_shortcuts_view_job_selected).addClassName('keyboard-shortcuts-view-job-selected');
      }
    }
  }

  function keyboard_shortcuts_view_job_prev() {
    if (typeof keyboard_shortcuts_view_job_names != 'undefined') {
      if (keyboard_shortcuts_view_job_names.length > 0) {
        keyboard_shortcuts_view_job_names.each(function(job) {
          $('job_' + job).removeClassName('keyboard-shortcuts-view-job-selected');
        });
        var idx = keyboard_shortcuts_view_job_names.indexOf(keyboard_shortcuts_view_job_selected) - 1;
        if (idx < 0) {
          idx = keyboard_shortcuts_view_job_names.length - 1;
        }
        keyboard_shortcuts_view_job_selected = keyboard_shortcuts_view_job_names[idx];
        $('job_' + keyboard_shortcuts_view_job_selected).addClassName('keyboard-shortcuts-view-job-selected');
      }
    }
  }

  function keyboard_shortcuts_view_job_open() {
    keyboard_shortcuts_hide_keyboard_shortcuts_help();
    if (typeof keyboard_shortcuts_view_job_selected != 'undefined') {
      window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_view + '/job/'
          + keyboard_shortcuts_view_job_selected;
    }
  }
}

0;
<commit_msg>fixing location for job workspace g-w<commit_after>/*
 * The MIT License
 *
 * Copyright (c) 2012, Jesse Farinacci
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

if (keyboard_shortcuts_enabled) {
  var keyboard_shortcuts_previous_code;
  var keyboard_shortcuts_previous_char;
  var keyboard_shortcuts_view_job_selected;

  Event.observe(window, 'load', function() {
    Event.observe(document, 'keypress', function(e) {

      /* try to play nicely with forms, so no keyboard shortcuts */
      var activeElement = document.activeElement;
      if (activeElement == null || 'INPUT' == activeElement.tagName) {
        return;
      }

      // ---

      var keyboard_shortcuts_code;

      if (!e) {
        e = window.event;
      }

      if (e.keyCode) {
        keyboard_shortcuts_code = e.keyCode;
      }

      else if (e.which) {
        keyboard_shortcuts_code = e.which;
      }

      /* always hide the shortcuts help, if user hits '?' again, re-display it */
      keyboard_shortcuts_hide_keyboard_shortcuts_help();

      var keyboard_shortcuts_character = String.fromCharCode(keyboard_shortcuts_code);

      switch (keyboard_shortcuts_character) {

        case '?':
          keyboard_shortcuts_show_keyboard_shortcuts_help();
          break;

        case '/':
          $('search-box').focus();
          break;

        case 'b':
          if (keyboard_shortcuts_is_job()) {
            window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/build?delay=0sec';
          }
          break;

        case 'c':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/changes';
            }
          }
          break;

        case 'C':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/configure';
            }
          }
          break;

        case 'h':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            window.location.href = keyboard_shortcuts_url;
          }
          break;

        case 'H':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_view()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_view + '/builds';
            }
          }
          break;

        case 'j':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            window.alert('keyboard_shortcuts_app_job_selector');
          }
          else {
            if (keyboard_shortcuts_is_view()) {
              keyboard_shortcuts_view_job_next();
            }
          }
          break;

        case 'k':
          if (keyboard_shortcuts_is_view()) {
            keyboard_shortcuts_view_job_prev();
          }
          break;

        case 'm':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/modules';
            }
            else if (keyboard_shortcuts_is_app()) {
              window.location.href = keyboard_shortcuts_url + '/manage';
            }
          }
          break;

        case 'n':
          if (keyboard_shortcuts_is_view()) {
            keyboard_shortcuts_view_job_next();
          }
          break;

        case 'o':
          if (keyboard_shortcuts_is_view()) {
            keyboard_shortcuts_view_job_open();
          }
          break;

        case 'p':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.alert('keyboard_shortcuts_job_permalink_selector');
            }
            else if (keyboard_shortcuts_is_app()) {
              window.location.href = keyboard_shortcuts_url + '/people';
            }
          }
          else {
            if (keyboard_shortcuts_is_view()) {
              keyboard_shortcuts_view_job_prev();
            }
          }
          break;

        case 'P':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/scmPollLog';
            }
            else if (keyboard_shortcuts_is_app()) {
              window.location.href = keyboard_shortcuts_url + '/pluginManager';
            }
          }
          break;

        case 'r':
          window.location.href = window.location.href;
          break;

        case 's':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job;
            }
          }
          break;

        case 'v':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            window.alert('keyboard_shortcuts_app_view_selector');
          }
          break;

        case 'w':
          if (keyboard_shortcuts_previous_character_was_character('g')) {
            if (keyboard_shortcuts_is_job()) {
              window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_job + '/ws';
            }
          }
          break;

        default:
          console.debug('code: ' + keyboard_shortcuts_code + ', character: ' + keyboard_shortcuts_character);
          break;
      }

      keyboard_shortcuts_previous_code = keyboard_shortcuts_code;
      keyboard_shortcuts_previous_character = String.fromCharCode(keyboard_shortcuts_code);
    });
  });

  function keyboard_shortcuts_is_job() {
    return typeof keyboard_shortcuts_is_job_page != 'undefined' && keyboard_shortcuts_is_job_page;
  }

  function keyboard_shortcuts_is_view() {
    return typeof keyboard_shortcuts_is_view_page != 'undefined' && keyboard_shortcuts_is_view_page;
  }

  function keyboard_shortcuts_show_keyboard_shortcuts_help() {
    $('keyboard-shortcuts-help').show();
  }

  function keyboard_shortcuts_hide_keyboard_shortcuts_help() {
    $('keyboard-shortcuts-help').hide();
  }

  function keyboard_shortcuts_previous_character_was_character(character) {
    if (typeof keyboard_shortcuts_previous_character == 'undefined') {
      return false;
    }

    if (typeof character == 'undefined') {
      return false;
    }

    return keyboard_shortcuts_previous_character == character;
  }

  function keyboard_shortcuts_view_job_next() {
    keyboard_shortcuts_hide_keyboard_shortcuts_help();
    if (typeof keyboard_shortcuts_view_job_names != 'undefined') {
      if (keyboard_shortcuts_view_job_names.length > 0) {
        keyboard_shortcuts_view_job_names.each(function(job) {
          $('job_' + job).removeClassName('keyboard-shortcuts-view-job-selected');
        });
        var idx = keyboard_shortcuts_view_job_names.indexOf(keyboard_shortcuts_view_job_selected) + 1;
        if (idx >= keyboard_shortcuts_view_job_names.length) {
          idx = 0;
        }
        keyboard_shortcuts_view_job_selected = keyboard_shortcuts_view_job_names[idx];
        $('job_' + keyboard_shortcuts_view_job_selected).addClassName('keyboard-shortcuts-view-job-selected');
      }
    }
  }

  function keyboard_shortcuts_view_job_prev() {
    if (typeof keyboard_shortcuts_view_job_names != 'undefined') {
      if (keyboard_shortcuts_view_job_names.length > 0) {
        keyboard_shortcuts_view_job_names.each(function(job) {
          $('job_' + job).removeClassName('keyboard-shortcuts-view-job-selected');
        });
        var idx = keyboard_shortcuts_view_job_names.indexOf(keyboard_shortcuts_view_job_selected) - 1;
        if (idx < 0) {
          idx = keyboard_shortcuts_view_job_names.length - 1;
        }
        keyboard_shortcuts_view_job_selected = keyboard_shortcuts_view_job_names[idx];
        $('job_' + keyboard_shortcuts_view_job_selected).addClassName('keyboard-shortcuts-view-job-selected');
      }
    }
  }

  function keyboard_shortcuts_view_job_open() {
    keyboard_shortcuts_hide_keyboard_shortcuts_help();
    if (typeof keyboard_shortcuts_view_job_selected != 'undefined') {
      window.location.href = keyboard_shortcuts_url + '/' + keyboard_shortcuts_url_view + '/job/'
          + keyboard_shortcuts_view_job_selected;
    }
  }
}

0;
<|endoftext|>


<commit_before>var express = require('express');
var passport = require('passport');
var mongoose = require('mongoose');
var fs = require('fs');
var sys = require('sys');
var router = express.Router();

var Comment = require('../models/comment.model.js');
var Idea = require('../models/idea.model.js');
var Users = require('../models/users.model.js');

module.exports.saveNewIdea = function(req, res) {

	console.log("save idea triggerd");
	console.log(req.body.idea);

  if(!req.body.user.id || !req.body.idea) {
    console.log("idea was not saved because of incomplete data");
    sendJSONresponse(res, 400, {
      "message": "user and idea required"
    });
    return;
  }

  var idea = new Idea();

  if(req.body.idea.scribble) {

  	var a = "useruploads/";
  	var b = "public/app/";
  	var now = Date.now();
  	var scribblePath = a.concat(now , ".png");
  	var scribbleSavePath = b.concat(a, now, ".png");
  	idea.scribble = scribblePath;
  	idea.img = scribblePath;

	// strip off the data: url prefix to get just the base64-encoded bytes
	var data = req.body.idea.scribble.replace(/^data:image\/\w+;base64,/, "");
	var buf = new Buffer(data, 'base64');
	fs.writeFile(scribbleSavePath, buf)

  } else {
  	idea.scribble = "";
  	idea.img = "";
  }

 	idea.author = req.body.user.id;
	idea.created = Date.now();
	idea.lastchanged = Date.now();
	idea.title = req.body.idea.title;
	idea.abstract = "";

	if(req.body.idea.description) {
		idea.description = req.body.idea.description;
	} else {
		idea.description = "no description";
	}

	// TODO: Disabled untill form passes objectIDs of users

	console.log("Contributors: ");
	console.log(req.body.idea.contributors);
	// if(req.body.idea.contributors) {
	// 	idea.contributors = req.body.idea.contributors;
	// } else {
	// 	idea.contributors = [];
	// }

	if(req.body.idea.milestones) {
		idea.milestones = req.body.idea.milestones;
	} else {
		idea.milestones = "no milestones";
	}

	if(req.body.idea.tags && req.body.idea.tags.length > 0) {
		// var tagNames = [];
		// for (var i in req.body.idea.tags) {
		//   tagNames.push(req.body.idea.tags[i]);
		// }
		// idea.tags = tagNames;
		idea.tags = req.body.idea.tags;
	} else {
		idea.tags = [];
	}

	if(req.body.idea.privacyType >= 0) {
		idea.privacyType = req.body.idea.privacyType;
	} else {
		idea.privacyType = 0;
	}

	if(req.body.idea.livetime && typeof req.body.idea.livetime === typeof 1) {
		idea.livetime = req.body.idea.livetime;
	} else {
		idea.livetime = 30;
	}

	console.log(idea);

	idea.save(function(err, room) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.json({
			  id : err
			});
		} else {
			console.log("Idea saved: ");
			console.log(room._id);

			res.status(200);
			res.json({
			  id : room._id
			});
		}

	});
};

module.exports.updateIdea = function(req, res) {

	console.log("update idea triggerd");
	console.log(req.body.idea);
	console.log(req.body.user);

  if(!req.body.user.id || !req.body.idea || !req.body.idea._id) {
    console.log("idea was not updated because of incomplete data");
    sendJSONresponse(res, 400, {
      "message": "user and idea required"
    });
    return;
  }

  Idea.findOne({ _id: req.body.idea._id }, function(err, ideaRes) {
		if (err) {
			console.log(err);
			res.status(400);
			res.json(err);
		} else {

			if (ideaRes.author != req.body.user.id ) {
				res.status(403);
				res.json("permission denied");
			} else {

			  var idea = new Idea();

			  if(req.body.idea.scribble) {

			  	var a = "useruploads/";
			  	var b = "public/app/";
			  	var now = Date.now();
			  	var scribblePath = a.concat(now , ".png");
			  	var scribbleSavePath = b.concat(a, now, ".png");
			  	idea.scribble = scribblePath;
			  	idea.img = scribblePath;

				// strip off the data: url prefix to get just the base64-encoded bytes
				var data = req.body.idea.scribble.replace(/^data:image\/\w+;base64,/, "");
				var buf = new Buffer(data, 'base64');
				fs.writeFile(scribbleSavePath, buf)

			  } else {
			  	idea.scribble = "";
			  	idea.img = "";
			  }

			 	idea._id = req.body.idea._id;
			 	idea.author = req.body.user.id;
				idea.created = Date.now();
				idea.lastchanged = Date.now();
				idea.title = req.body.idea.title;
				idea.abstract = "";

				if(req.body.idea.description) {
					idea.description = req.body.idea.description;
				}

				// TODO: Disabled untill form passes objectIDs of users
				// if(req.body.idea.contributors) {
				// 	idea.contributors = req.body.idea.contributors;
				// } else {
				// 	idea.contributors = [];
				// }

				if(req.body.idea.milestones) {
					idea.milestones = req.body.idea.milestones;
				}

				if(req.body.idea.tags && req.body.idea.tags.length > 0) {
					// var tagNames = [];
					// for (var i in req.body.idea.tags) {
					//   tagNames.push(req.body.idea.tags[i].name);
					// }
					// idea.tags = tagNames;
					idea.tags = req.body.idea.tags;
				}

				if(req.body.idea.privacyType >= 0) {
					idea.privacyType = req.body.idea.privacyType;
				}

				console.log(idea);

				Idea.update({ _id: idea._id} , {
					"description": idea.description,
					"abstract": idea.abstract,
					"title": idea.title,
					"img": idea.img,
					"scribble": idea.scribble,
					"tags": idea.tags,
					"milestones": idea.milestones,
					"contributors": idea.contributors,
					"lastchanged": Date.now()
				}, function(err, room) {

					if (err) {
						console.log("error: ");
						console.log(err);
						res.json({
						  id : err
						});
					} else {
						console.log("Idea saved: ");
						console.log(room._id);

						res.status(200);
						res.json({
						  id : room._id
						});
					}
				});

				// idea.save(function(err, room) {

				// 	if (err) {
				// 		console.log("error: ");
				// 		console.log(err);
				// 		res.json({
				// 		  id : err
				// 		});
				// 	} else {
				// 		console.log("Idea saved: ");
				// 		console.log(room._id);
				// 		console.log(room.img);

				// 		res.status(200);
				// 		res.json({
				// 		  id : room._id
				// 		});
				// 	}
				// });

			}
		}
	});
};

module.exports.followIdea = function(req, res) {
	//we need: ideaId, userId

	if(!req.body.user._id || !req.body.ideaId) {
	    console.log("was not saved because of incomplete data");
	    sendJSONresponse(res, 400, {
	      "message": "user and ideaId required"
	    });
	    return;
	  }

	  Users.update({ _id: req.body.user._id },
		   { $push: { followedideas: req.body.ideaId } }, function(err, room) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.json({
			  id : err
			});
		} else {
			console.log("followed");

			res.status(200);
			res.json({
			  id : room._id
			});
		}

	});
};

module.exports.likeIdea = function(req, res) {
	//we need: ideaId, userId

		if(!req.body.user._id || !req.body.ideaId) {
	    console.log("was not saved because of incomplete data");
	    sendJSONresponse(res, 400, {
	      "message": "user and ideaId required"
	    });
	    return;
	  }

	  Idea.update({ _id: req.body.ideaId },
		   { $push: { likes: req.body.user._id } }, function(err, room) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.json({
			  id : err
			});
		} else {
			console.log("liked: ");
			console.log(room._id);

			res.status(200);
			res.json({
			  id : room._id
			});
		}

	});
};

module.exports.unFollowIdea = function(req, res) {
	//we need: ideaId, userId

	if(!req.body.user._id || !req.body.ideaId) {
	    console.log("was not saved because of incomplete data");
	    sendJSONresponse(res, 400, {
	      "message": "user and ideaId required"
	    });
	    return;
	  }

	  Users.update({ _id: req.body.user._id },
		   { $pull: { followedideas: req.body.ideaId } }, function(err, room) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.json({
			  id : err
			});
		} else {
			console.log("unfollowed: ");

			res.status(200);
			res.json({
			  id : room._id
			});
		}

	});
};

module.exports.dislikeIdea = function(req, res) {
	//we need: ideaId, userId

		if(!req.body.user._id || !req.body.ideaId) {
	    console.log("was not saved because of incomplete data");
	    sendJSONresponse(res, 400, {
	      "message": "user and ideaId required"
	    });
	    return;
	  }

	  Idea.update({ _id: req.body.ideaId },
		   { $pull: { likes: req.body.user._id } }, function(err, room) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.json({
			  id : err
			});
		} else {
			console.log("liked: ");
			console.log(room._id);

			res.status(200);
			res.json({
			  id : room._id
			});
		}

	});
};

module.exports.writeComment = function(req, res) {

	console.log("save idea triggerd");
	console.log(req.body.comment);

  if(!req.body.user._id || !req.body.comment || !req.body.ideaId || !req.body.comment.text) {
    console.log("comment was not saved because of incomplete data");
    sendJSONresponse(res, 400, {
      "message": "comment was not saved because of incomplete data"
    });
    return;
  }

	var comment = new Comment();

	comment.user = req.body.user.id;
	comment.ikeIdeaStatus = req.body.comment.ikeIdeaStatus;
	comment.newInputStatus = req.body.comment.newInputStatus;
	comment.troubleStatus = req.body.comment.troubleStatus;
	comment.otherreaction = req.body.comment.otherreaction;
	comment.text = req.body.comment.text;
	comment.idea = req.body.ideaId;
	comment.created = Date.now();

	console.log(comment);

	comment.save(function(err, doc) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.status(400);
			res.json(err);
		} else {
			console.log("Comment saved: ");
			console.log(doc._id);

			res.status(200);
			res.json(doc);
		}

	});

};
<commit_msg>updateIdea writes privacyType<commit_after>var express = require('express');
var passport = require('passport');
var mongoose = require('mongoose');
var fs = require('fs');
var sys = require('sys');
var router = express.Router();

var Comment = require('../models/comment.model.js');
var Idea = require('../models/idea.model.js');
var Users = require('../models/users.model.js');

module.exports.saveNewIdea = function(req, res) {

	console.log("save idea triggerd");
	console.log(req.body.idea);

  if(!req.body.user.id || !req.body.idea) {
    console.log("idea was not saved because of incomplete data");
    sendJSONresponse(res, 400, {
      "message": "user and idea required"
    });
    return;
  }

  var idea = new Idea();

  if(req.body.idea.scribble) {

  	var a = "useruploads/";
  	var b = "public/app/";
  	var now = Date.now();
  	var scribblePath = a.concat(now , ".png");
  	var scribbleSavePath = b.concat(a, now, ".png");
  	idea.scribble = scribblePath;
  	idea.img = scribblePath;

	// strip off the data: url prefix to get just the base64-encoded bytes
	var data = req.body.idea.scribble.replace(/^data:image\/\w+;base64,/, "");
	var buf = new Buffer(data, 'base64');
	fs.writeFile(scribbleSavePath, buf)

  } else {
  	idea.scribble = "";
  	idea.img = "";
  }

 	idea.author = req.body.user.id;
	idea.created = Date.now();
	idea.lastchanged = Date.now();
	idea.title = req.body.idea.title;
	idea.abstract = "";

	if(req.body.idea.description) {
		idea.description = req.body.idea.description;
	} else {
		idea.description = "no description";
	}

	// TODO: Disabled untill form passes objectIDs of users

	console.log("Contributors: ");
	console.log(req.body.idea.contributors);
	// if(req.body.idea.contributors) {
	// 	idea.contributors = req.body.idea.contributors;
	// } else {
	// 	idea.contributors = [];
	// }

	if(req.body.idea.milestones) {
		idea.milestones = req.body.idea.milestones;
	} else {
		idea.milestones = "no milestones";
	}

	if(req.body.idea.tags && req.body.idea.tags.length > 0) {
		// var tagNames = [];
		// for (var i in req.body.idea.tags) {
		//   tagNames.push(req.body.idea.tags[i]);
		// }
		// idea.tags = tagNames;
		idea.tags = req.body.idea.tags;
	} else {
		idea.tags = [];
	}

	if(req.body.idea.privacyType >= 0) {
		idea.privacyType = req.body.idea.privacyType;
	} else {
		idea.privacyType = 0;
	}

	if(req.body.idea.livetime && typeof req.body.idea.livetime === typeof 1) {
		idea.livetime = req.body.idea.livetime;
	} else {
		idea.livetime = 30;
	}

	console.log(idea);

	idea.save(function(err, room) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.json({
			  id : err
			});
		} else {
			console.log("Idea saved: ");
			console.log(room._id);

			res.status(200);
			res.json({
			  id : room._id
			});
		}

	});
};

module.exports.updateIdea = function(req, res) {

	console.log("update idea triggerd");
	console.log(req.body.idea);
	console.log(req.body.user);

  if(!req.body.user.id || !req.body.idea || !req.body.idea._id) {
    console.log("idea was not updated because of incomplete data");
    sendJSONresponse(res, 400, {
      "message": "user and idea required"
    });
    return;
  }

  Idea.findOne({ _id: req.body.idea._id }, function(err, ideaRes) {
		if (err) {
			console.log(err);
			res.status(400);
			res.json(err);
		} else {

			if (ideaRes.author != req.body.user.id ) {
				res.status(403);
				res.json("permission denied");
			} else {

			  var idea = new Idea();

			  if(req.body.idea.scribble) {

			  	var a = "useruploads/";
			  	var b = "public/app/";
			  	var now = Date.now();
			  	var scribblePath = a.concat(now , ".png");
			  	var scribbleSavePath = b.concat(a, now, ".png");
			  	idea.scribble = scribblePath;
			  	idea.img = scribblePath;

				// strip off the data: url prefix to get just the base64-encoded bytes
				var data = req.body.idea.scribble.replace(/^data:image\/\w+;base64,/, "");
				var buf = new Buffer(data, 'base64');
				fs.writeFile(scribbleSavePath, buf)

			  } else {
			  	idea.scribble = "";
			  	idea.img = "";
			  }

			 	idea._id = req.body.idea._id;
			 	idea.author = req.body.user.id;
				idea.created = Date.now();
				idea.lastchanged = Date.now();
				idea.title = req.body.idea.title;
				idea.abstract = "";

				if(req.body.idea.description) {
					idea.description = req.body.idea.description;
				}

				// TODO: Disabled untill form passes objectIDs of users
				// if(req.body.idea.contributors) {
				// 	idea.contributors = req.body.idea.contributors;
				// } else {
				// 	idea.contributors = [];
				// }

				if(req.body.idea.milestones) {
					idea.milestones = req.body.idea.milestones;
				}

				if(req.body.idea.tags && req.body.idea.tags.length > 0) {
					// var tagNames = [];
					// for (var i in req.body.idea.tags) {
					//   tagNames.push(req.body.idea.tags[i].name);
					// }
					// idea.tags = tagNames;
					idea.tags = req.body.idea.tags;
				}

				if(req.body.idea.privacyType >= 0) {
					idea.privacyType = req.body.idea.privacyType;
				}

				console.log(idea);

				Idea.update({ _id: idea._id} , {
					"description": idea.description,
					"abstract": idea.abstract,
					"title": idea.title,
					"img": idea.img,
					"scribble": idea.scribble,
					"tags": idea.tags,
					"milestones": idea.milestones,
					"privacyType": idea.privacyType,
					"contributors": idea.contributors,
					"lastchanged": Date.now()
				}, function(err, room) {

					if (err) {
						console.log("error: ");
						console.log(err);
						res.json({
						  id : err
						});
					} else {
						console.log("Idea saved: ");
						console.log(room._id);

						res.status(200);
						res.json({
						  id : room._id
						});
					}
				});

				// idea.save(function(err, room) {

				// 	if (err) {
				// 		console.log("error: ");
				// 		console.log(err);
				// 		res.json({
				// 		  id : err
				// 		});
				// 	} else {
				// 		console.log("Idea saved: ");
				// 		console.log(room._id);
				// 		console.log(room.img);

				// 		res.status(200);
				// 		res.json({
				// 		  id : room._id
				// 		});
				// 	}
				// });

			}
		}
	});
};

module.exports.followIdea = function(req, res) {
	//we need: ideaId, userId

	if(!req.body.user._id || !req.body.ideaId) {
	    console.log("was not saved because of incomplete data");
	    sendJSONresponse(res, 400, {
	      "message": "user and ideaId required"
	    });
	    return;
	  }

	  Users.update({ _id: req.body.user._id },
		   { $push: { followedideas: req.body.ideaId } }, function(err, room) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.json({
			  id : err
			});
		} else {
			console.log("followed");

			res.status(200);
			res.json({
			  id : room._id
			});
		}

	});
};

module.exports.likeIdea = function(req, res) {
	//we need: ideaId, userId

		if(!req.body.user._id || !req.body.ideaId) {
	    console.log("was not saved because of incomplete data");
	    sendJSONresponse(res, 400, {
	      "message": "user and ideaId required"
	    });
	    return;
	  }

	  Idea.update({ _id: req.body.ideaId },
		   { $push: { likes: req.body.user._id } }, function(err, room) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.json({
			  id : err
			});
		} else {
			console.log("liked: ");
			console.log(room._id);

			res.status(200);
			res.json({
			  id : room._id
			});
		}

	});
};

module.exports.unFollowIdea = function(req, res) {
	//we need: ideaId, userId

	if(!req.body.user._id || !req.body.ideaId) {
	    console.log("was not saved because of incomplete data");
	    sendJSONresponse(res, 400, {
	      "message": "user and ideaId required"
	    });
	    return;
	  }

	  Users.update({ _id: req.body.user._id },
		   { $pull: { followedideas: req.body.ideaId } }, function(err, room) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.json({
			  id : err
			});
		} else {
			console.log("unfollowed: ");

			res.status(200);
			res.json({
			  id : room._id
			});
		}

	});
};

module.exports.dislikeIdea = function(req, res) {
	//we need: ideaId, userId

		if(!req.body.user._id || !req.body.ideaId) {
	    console.log("was not saved because of incomplete data");
	    sendJSONresponse(res, 400, {
	      "message": "user and ideaId required"
	    });
	    return;
	  }

	  Idea.update({ _id: req.body.ideaId },
		   { $pull: { likes: req.body.user._id } }, function(err, room) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.json({
			  id : err
			});
		} else {
			console.log("liked: ");
			console.log(room._id);

			res.status(200);
			res.json({
			  id : room._id
			});
		}

	});
};

module.exports.writeComment = function(req, res) {

	console.log("save idea triggerd");
	console.log(req.body.comment);

  if(!req.body.user._id || !req.body.comment || !req.body.ideaId || !req.body.comment.text) {
    console.log("comment was not saved because of incomplete data");
    sendJSONresponse(res, 400, {
      "message": "comment was not saved because of incomplete data"
    });
    return;
  }

	var comment = new Comment();

	comment.user = req.body.user.id;
	comment.ikeIdeaStatus = req.body.comment.ikeIdeaStatus;
	comment.newInputStatus = req.body.comment.newInputStatus;
	comment.troubleStatus = req.body.comment.troubleStatus;
	comment.otherreaction = req.body.comment.otherreaction;
	comment.text = req.body.comment.text;
	comment.idea = req.body.ideaId;
	comment.created = Date.now();

	console.log(comment);

	comment.save(function(err, doc) {

		if (err) {
			console.log("error: ");
			console.log(err);
			res.status(400);
			res.json(err);
		} else {
			console.log("Comment saved: ");
			console.log(doc._id);

			res.status(200);
			res.json(doc);
		}

	});

};
<|endoftext|>


<commit_before>/**
 * @module loader_type_bundle
 * @description Load BEM bundle (JS+CSS) from external URL.
 */

modules.define('loader_type_bundle', function(provide) {

var LOADING_TIMEOUT = 20000,
    global = this.global,
    doc = document,
    head,
    bundles = {},

    handleError = function(bundleId) {
        var bundleDesc = bundles[bundleId];

        if(!bundleDesc) return;

        var fns = bundleDesc.errorFns,
            fn;

        clearTimeout(bundleDesc.timer);

        while(fn = fns.shift()) fn();
        delete bundles[bundleId];
    },

    appendCss = function(css) {
        var style = doc.createElement('style');
        style.type = 'text/css';
        head.appendChild(style); // ie needs to insert style before setting content
        style.styleSheet?
            style.styleSheet.cssText = css :
            style.appendChild(doc.createTextNode(css));
    },

    /**
     * Loads bundle
     * @exports
     * @param {String} id
     * @param {String} url
     * @param {Function} onSuccess
     * @param {Function} [onError]
     */
    load = function(id, url, onSuccess, onError) {
        var bundle = bundles[id];
        if(bundle) {
            if(bundle.successFns) { // bundle is being loaded
                bundle.successFns.push(onSuccess);
                onError && bundle.errorFns.push(onError);
            } else { // bundle was loaded before
                setTimeout(onSuccess, 0);
            }
            return;
        }

        var script = doc.createElement('script'),
            errorFn = function() {
                handleError(id);
            };

        script.type = 'text/javascript';
        script.charset = 'utf-8';
        script.src = url;
        script.onerror = errorFn; // for browsers that support
        setTimeout(function() {
            (head || (head = doc.getElementsByTagName('head')[0])).insertBefore(script, head.firstChild);
        }, 0);

        bundles[id] = {
            successFns : [onSuccess],
            errorFns : onError? [onError] : [],
            timer : setTimeout(errorFn, LOADING_TIMEOUT)
        };
    };

load._loaded = function(bundle) {
    var bundleDesc = bundles[bundle.id];

    if(!bundleDesc) return;

    clearTimeout(bundleDesc.timer);

    bundle.js && bundle.js.call(global);

    bundle.css && appendCss(bundle.css);

    if(bundle.hcss) {
        var styles = [],
            _ycssjs = window._ycssjs;

        bundle.hcss.forEach(function(hsh) {
            if(_ycssjs) {
                if(hsh[0] in _ycssjs) return;
                _ycssjs(hsh[0]);
            }

            styles.push(hsh[1]);
        });

        styles.length && appendCss(styles.join(''));
    }

    function onSuccess() {
        var fns = bundleDesc.successFns, fn;
        while(fn = fns.shift()) fn();
        delete bundleDesc.successFns;
    }

    modules.isDefined('i-bem__dom_init')?
        modules.require(['i-bem__dom_init'], onSuccess) :
        onSuccess();
};

provide(load);

});
<commit_msg>loader_type_bundle: increase error timeout<commit_after>/**
 * @module loader_type_bundle
 * @description Load BEM bundle (JS+CSS) from external URL.
 */

modules.define('loader_type_bundle', function(provide) {

var LOADING_TIMEOUT = 30000,
    global = this.global,
    doc = document,
    head,
    bundles = {},

    handleError = function(bundleId) {
        var bundleDesc = bundles[bundleId];

        if(!bundleDesc) return;

        var fns = bundleDesc.errorFns,
            fn;

        clearTimeout(bundleDesc.timer);

        while(fn = fns.shift()) fn();
        delete bundles[bundleId];
    },

    appendCss = function(css) {
        var style = doc.createElement('style');
        style.type = 'text/css';
        head.appendChild(style); // ie needs to insert style before setting content
        style.styleSheet?
            style.styleSheet.cssText = css :
            style.appendChild(doc.createTextNode(css));
    },

    /**
     * Loads bundle
     * @exports
     * @param {String} id
     * @param {String} url
     * @param {Function} onSuccess
     * @param {Function} [onError]
     */
    load = function(id, url, onSuccess, onError) {
        var bundle = bundles[id];
        if(bundle) {
            if(bundle.successFns) { // bundle is being loaded
                bundle.successFns.push(onSuccess);
                onError && bundle.errorFns.push(onError);
            } else { // bundle was loaded before
                setTimeout(onSuccess, 0);
            }
            return;
        }

        var script = doc.createElement('script'),
            errorFn = function() {
                handleError(id);
            };

        script.type = 'text/javascript';
        script.charset = 'utf-8';
        script.src = url;
        script.onerror = errorFn; // for browsers that support
        setTimeout(function() {
            (head || (head = doc.getElementsByTagName('head')[0])).insertBefore(script, head.firstChild);
        }, 0);

        bundles[id] = {
            successFns : [onSuccess],
            errorFns : onError? [onError] : [],
            timer : setTimeout(errorFn, LOADING_TIMEOUT)
        };
    };

load._loaded = function(bundle) {
    var bundleDesc = bundles[bundle.id];

    if(!bundleDesc) return;

    clearTimeout(bundleDesc.timer);

    bundle.js && bundle.js.call(global);

    bundle.css && appendCss(bundle.css);

    if(bundle.hcss) {
        var styles = [],
            _ycssjs = window._ycssjs;

        bundle.hcss.forEach(function(hsh) {
            if(_ycssjs) {
                if(hsh[0] in _ycssjs) return;
                _ycssjs(hsh[0]);
            }

            styles.push(hsh[1]);
        });

        styles.length && appendCss(styles.join(''));
    }

    function onSuccess() {
        var fns = bundleDesc.successFns, fn;
        while(fn = fns.shift()) fn();
        delete bundleDesc.successFns;
    }

    modules.isDefined('i-bem__dom_init')?
        modules.require(['i-bem__dom_init'], onSuccess) :
        onSuccess();
};

provide(load);

});
<|endoftext|>


<commit_before>import LabelPair from '../LabelPair';
import IconSVG from '../../IconSVG';
import React from 'react';
import Typography from '../../Typography';
import classNames from 'classnames';
import styles from './styles.css';
const PropTypes = React.PropTypes;

function ListCompositeActivity(props) {
    return (

            <IconSVG
                className={styles.icon}
                icon={props.iconSVG}
                size={"standard"}
            />

                <Typography className={styles.typo}
                    type="bodyTextTitle"
                >
                    {props.title}
                </Typography>
                <LabelPair
                    co2={props.co2}
                    onClick={props.onClick}
                    points={props.points}
                />

    );
}

ListCompositeActivity.propTypes = {
    className: PropTypes.string,
    co2: PropTypes.number,
    iconSVG: PropTypes.string,
    onClick: PropTypes.func,
    points: PropTypes.number,
    title: PropTypes.string
};

export default ListCompositeActivity;
<commit_msg>List Composite Activity onClick<commit_after>import LabelPair from '../LabelPair';
import IconSVG from '../../IconSVG';
import React from 'react';
import Typography from '../../Typography';
import classNames from 'classnames';
import styles from './styles.css';
const PropTypes = React.PropTypes;

function ListCompositeActivity(props) {
    return (

            <IconSVG
                className={styles.icon}
                icon={props.iconSVG}
                onClick={props.onIconClick}
                size={"standard"}
            />

                <Typography
                    className={styles.typo}
                    onClick={props.onTextClick}
                    type={"bodyTextTitle"}
                >
                    {props.title}
                </Typography>
                <LabelPair
                    co2={props.co2}
                    onClick={props.onLabelClick}
                    points={props.points}
                />

    );
}

ListCompositeActivity.propTypes = {
    className: PropTypes.string,
    co2: PropTypes.number,
    iconSVG: PropTypes.string,
    onIconClick: PropTypes.func,
    onLabelClick: PropTypes.func,
    onTextClick: PropTypes.func,
    points: PropTypes.number,
    title: PropTypes.string
};

export default ListCompositeActivity;
<|endoftext|>


<commit_before>Space.eventSourcing.Aggregate.extend(Todos, 'TodoList', {

  FIELDS: {
    name: null,
    todos: null
  },

  commandMap() {
    return {
      'Todos.CreateTodoList': this._createTodoList,
      'Todos.CreateTodoItem': this._createTodoItem
    };
  },

  eventMap() {
    return {
      'Todos.TodoListCreated': this._handleNewTodoList,
      'Todos.TodoItemCreated': this._handleNewTodoItem
    };
  },

  // ============= COMMAND HANDLERS =============

  _createTodoList(command) {
    this.record(new Todos.TodoListCreated(this._eventPropsFromCommand(command)));
  },

  _createTodoItem(command) {
    this.record(new Todos.TodoItemCreated(this._eventPropsFromCommand(command)));
  },

  // ============= EVENT HANDLERS ============

  _handleNewTodoList(event) {
    this.todos = [];
  },

  _handleNewTodoItem(event) {
    let todoItem = new Todos.TodoItem(new Guid());
    todoItem.title = event.title;
    todoItem.isCompleted = event.isCompleted;
    this.todos.push(todoItem);
  }

});
<commit_msg>Fixes TodoList aggregate<commit_after>Space.eventSourcing.Aggregate.extend(Todos, 'TodoList', {

  fields: {
    name: null,
    todos: null
  },

  commandMap() {
    return {
      'Todos.CreateTodoList': this._createTodoList,
      'Todos.CreateTodoItem': this._createTodoItem
    };
  },

  eventMap() {
    return {
      'Todos.TodoListCreated': this._handleNewTodoList,
      'Todos.TodoItemCreated': this._handleNewTodoItem
    };
  },

  // ============= COMMAND HANDLERS =============

  _createTodoList(command) {
    this.record(new Todos.TodoListCreated(this._eventPropsFromCommand(command)));
  },

  _createTodoItem(command) {
    this.record(new Todos.TodoItemCreated(this._eventPropsFromCommand(command)));
  },

  // ============= EVENT HANDLERS ============

  _handleNewTodoList(event) {
    this.todos = [];
  },

  _handleNewTodoItem(event) {
    let todoItem = new Todos.TodoItem(new Guid());
    todoItem.title = event.title;
    todoItem.isCompleted = event.isCompleted;
    this.todos.push(todoItem);
  }

});
<|endoftext|>


<commit_before>(function($) {
	'use strict';

	var $body = $('body');
	$body.on('ratings.load',function(e, query) {
		query.t = query.t
				.replace('[dt./OV]', '')
				.replace('[OV]', '')
				.replace('[OV/OmU]', '');

		$.getJSON('https://www.omdbapi.com/', query, function(data) {
			$body.trigger('ratings.return', [data]);
		});
	});
})(window.jQuery);<commit_msg>fix indention<commit_after>(function($) {
	'use strict';

	var $body = $('body');
	$body.on('ratings.load',function(e, query) {
		query.t = query.t
			.replace('[dt./OV]', '')
			.replace('[OV]', '')
			.replace('[OV/OmU]', '');

		$.getJSON('https://www.omdbapi.com/', query, function(data) {
			$body.trigger('ratings.return', [data]);
		});
	});
})(window.jQuery);
<|endoftext|>


<commit_before>'use strict';

const CSP = {
    defaultSrc: ['\'none\''],
    baseUri: ['\'self\''],
    formAction: [
        'platform.twitter.com',
        'syndication.twitter.com'
    ],
    frameAncestors: ['\'none\''],
    scriptSrc: [
        '\'self\'',
        '\'unsafe-inline\'',
        'stackpath.bootstrapcdn.com',
        'www.google-analytics.com',
        'code.jquery.com',
        'platform.twitter.com',
        'cdn.syndication.twimg.com',
        'api.github.com',
        'cdn.carbonads.com',
        'srv.carbonads.net',
        'adn.fusionads.net',
        'fallbacks.carbonads.com',
        (req, res) => `'nonce-${res.locals.nonce}'`
    ],
    styleSrc: [
        '\'self\'',
        '\'unsafe-inline\'',
        'stackpath.bootstrapcdn.com',
        'fonts.googleapis.com',
        '*.twimg.com',
        'platform.twitter.com'
    ],
    imgSrc: [
        '\'self\'',
        'data:',
        'www.google-analytics.com',
        'bootswatch.com',
        '*.twitter.com',
        '*.twimg.com',
        'stats.g.doubleclick.net',
        'srv.carbonads.net',
        'assets.servedby-buysellads.com',
        'ad.doubleclick.net',
        '*.convertro.com',
        '*.c3tag.com',
        '*.2mdn.net',
        'launchbit.com',
        'www.launchbit.com'
    ],
    fontSrc: [
        '\'self\'',
        'stackpath.bootstrapcdn.com',
        'fonts.gstatic.com'
    ],
    frameSrc: [
        '\'self\'',
        'platform.twitter.com',
        'syndication.twitter.com',
        'ghbtns.com'
    ],
    childSrc: [
        '\'self\'',
        'platform.twitter.com',
        'syndication.twitter.com',
        'ghbtns.com'
    ],
    connectSrc: [
        'syndication.twitter.com'
    ],
    manifestSrc: ['\'self\'']
};

module.exports = CSP;

// vim: ft=javascript sw=4 sts=4 et:
<commit_msg>CSP: Add `fallbacks.carbonads.com` in img-src.<commit_after>'use strict';

const CSP = {
    defaultSrc: ['\'none\''],
    baseUri: ['\'self\''],
    formAction: [
        'platform.twitter.com',
        'syndication.twitter.com'
    ],
    frameAncestors: ['\'none\''],
    scriptSrc: [
        '\'self\'',
        '\'unsafe-inline\'',
        'stackpath.bootstrapcdn.com',
        'www.google-analytics.com',
        'code.jquery.com',
        'platform.twitter.com',
        'cdn.syndication.twimg.com',
        'api.github.com',
        'cdn.carbonads.com',
        'srv.carbonads.net',
        'adn.fusionads.net',
        'fallbacks.carbonads.com',
        (req, res) => `'nonce-${res.locals.nonce}'`
    ],
    styleSrc: [
        '\'self\'',
        '\'unsafe-inline\'',
        'stackpath.bootstrapcdn.com',
        'fonts.googleapis.com',
        '*.twimg.com',
        'platform.twitter.com'
    ],
    imgSrc: [
        '\'self\'',
        'data:',
        'www.google-analytics.com',
        'bootswatch.com',
        '*.twitter.com',
        '*.twimg.com',
        'stats.g.doubleclick.net',
        'fallbacks.carbonads.com',
        'srv.carbonads.net',
        'assets.servedby-buysellads.com',
        'ad.doubleclick.net',
        '*.convertro.com',
        '*.c3tag.com',
        '*.2mdn.net',
        'launchbit.com',
        'www.launchbit.com'
    ],
    fontSrc: [
        '\'self\'',
        'stackpath.bootstrapcdn.com',
        'fonts.gstatic.com'
    ],
    frameSrc: [
        '\'self\'',
        'platform.twitter.com',
        'syndication.twitter.com',
        'ghbtns.com'
    ],
    childSrc: [
        '\'self\'',
        'platform.twitter.com',
        'syndication.twitter.com',
        'ghbtns.com'
    ],
    connectSrc: [
        'syndication.twitter.com'
    ],
    manifestSrc: ['\'self\'']
};

module.exports = CSP;

// vim: ft=javascript sw=4 sts=4 et:
<|endoftext|>


<commit_before>basePath = '../';

files = [
    JASMINE,
    JASMINE_ADAPTER,
    "app/components/jquery/jquery.js",
    "app/components/jquery-ui/ui/jquery-ui.js",
    "app/components/angular/angular.js",
    "app/components/angular-sanitize/angular-sanitize.js",
    "app/components/angular-route/angular-route.js",
    "app/components/underscore/underscore.js",
    "app/components/angular-ui-bootstrap-bower/ui-bootstrap-tpls.js",
    "app/components/angular-ui-date/src/date.js",
    "app/components/angular-ui-select2/src/select2.js",
    "app/components/ngInfiniteScroll/ng-infinite-scroll.js",
    "app/components/ng-grid/build/ng-grid.js",
    "app/components/select2/select2.js",
    'app/components/angular-mocks/angular-mocks.js',
    'app/components/angular-elastic/elastic.js',
    'app/components/angular-dragdrop/src/angular-dragdrop.js',
    'app/js/forms-angular.js',
    'app/js/**/*.js',
    'app/demo/demo.js',
    'app/demo/bespoke-field.js',
    'test/unit/**/*.js'

    //load templates and use html2js to add to the $templateCache
    , 'app/template/**/*.html'
];

//use html2js to load the templates to the $templateCache
preprocessors = { 'app/template/**/*.html': 'html2js'};

autoWatch = true;

browsers = ['PhantomJS'];

junitReporter = {
    outputFile: 'test_out/unit.xml',
    suite: 'unit'
};
<commit_msg>added spec for drag-drop and disabled as not complete<commit_after>basePath = '../';

files = [
    JASMINE,
    JASMINE_ADAPTER,
    "app/components/jquery/jquery.js",
    "app/components/jquery-ui/ui/jquery-ui.js",
    "app/components/angular/angular.js",
    "app/components/angular-sanitize/angular-sanitize.js",
    "app/components/angular-route/angular-route.js",
    "app/components/underscore/underscore.js",
    "app/components/angular-ui-bootstrap-bower/ui-bootstrap-tpls.js",
    "app/components/angular-ui-date/src/date.js",
    "app/components/angular-ui-select2/src/select2.js",
    "app/components/ngInfiniteScroll/ng-infinite-scroll.js",
    "app/components/ng-grid/build/ng-grid.js",
    "app/components/select2/select2.js",
    'app/components/angular-mocks/angular-mocks.js',
    'app/components/angular-elastic/elastic.js',
    'app/components/angular-dragdrop/src/angular-dragdrop.js',
    'app/components/angular-ui-sortable/src/sortable.js',
    'app/js/forms-angular.js',
    'app/js/**/*.js',
    'app/demo/demo.js',
    'app/demo/bespoke-field.js',
    'test/unit/**/*.js'

    //load templates and use html2js to add to the $templateCache
    , 'app/template/**/*.html'
];

//use html2js to load the templates to the $templateCache
preprocessors = { 'app/template/**/*.html': 'html2js'};

autoWatch = true;

browsers = ['PhantomJS'];

junitReporter = {
    outputFile: 'test_out/unit.xml',
    suite: 'unit'
};
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

module.exports = function (config) {
  var testWebpackConfig = require('./webpack.test.js')({ env: 'test' });

  var configuration = {

    // base path that will be used to resolve all patterns (e.g. files, exclude)
    basePath: '',

    /*
     * Frameworks to use
     *
     * available frameworks: https://npmjs.org/browse/keyword/karma-adapter
     */
    frameworks: ['jasmine'],

    // list of files to exclude
    exclude: [],

    client: {
      captureConsole: false
    },

	captureTimeout = 60000,
	browserDisconnectTimeout = 2000,
	browserDisconnectTolerance = 0,
	browserNoActivityTimeout = 10000,

	/*
     * list of files / patterns to load in the browser
     *
     * we are building the test environment in ./spec-bundle.js
     */
    files: [
      { pattern: './config/spec-bundle.js', watched: false },
      { pattern: './src/assets/**/*', watched: false, included: false, served: true, nocache: false }
    ],

    /*
     * By default all assets are served at http://localhost:[PORT]/base/
     */
    proxies: {
      "/assets/": "/base/src/assets/"
    },

    /*
     * preprocess matching files before serving them to the browser
     * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
     */
    preprocessors: { './config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] },

    // Webpack Config at ./webpack.test.js
    webpack: testWebpackConfig,

    coverageReporter: {
      type: 'in-memory'
    },

    remapCoverageReporter: {
      'text-summary': null,
      json: './coverage/coverage.json',
      html: './coverage/html'
    },

    // Webpack please don't spam the console when running in karma!
    webpackMiddleware: {
      // webpack-dev-middleware configuration
      // i.e.
      noInfo: true,
      // and use stats to turn off verbose output
      stats: {
        // options i.e.
        chunks: false
      }
    },

    /*
     * test results reporter to use
     *
     * possible values: 'dots', 'progress'
     * available reporters: https://npmjs.org/browse/keyword/karma-reporter
     */
    reporters: ['mocha', 'coverage', 'remap-coverage'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    /*
     * level of logging
     * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
     */
    logLevel: config.LOG_WARN,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    /*
     * start these browsers
     * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
     */
    browsers: [
      //'Chrome'
	  'PhantomJS'
    ],

    customLaunchers: {
      ChromeTravisCi: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    /*
     * Continuous Integration mode
     * if true, Karma captures browsers, runs the tests and exits
     */
    singleRun: false
  };

  if (process.env.TRAVIS) {
    configuration.browsers = [
      'ChromeTravisCi'
    ];
  }

  config.set(configuration);
};
<commit_msg>tests v9<commit_after>/**
 * @author: @AngularClass
 */

module.exports = function (config) {
  var testWebpackConfig = require('./webpack.test.js')({ env: 'test' });

  var configuration = {

    // base path that will be used to resolve all patterns (e.g. files, exclude)
    basePath: '',

    /*
     * Frameworks to use
     *
     * available frameworks: https://npmjs.org/browse/keyword/karma-adapter
     */
    frameworks: ['jasmine'],

    // list of files to exclude
    exclude: [],

    client: {
      captureConsole: false
    },

	/*
     * list of files / patterns to load in the browser
     *
     * we are building the test environment in ./spec-bundle.js
     */
    files: [
      { pattern: './config/spec-bundle.js', watched: false },
      { pattern: './src/assets/**/*', watched: false, included: false, served: true, nocache: false }
    ],

    /*
     * By default all assets are served at http://localhost:[PORT]/base/
     */
    proxies: {
      "/assets/": "/base/src/assets/"
    },

    /*
     * preprocess matching files before serving them to the browser
     * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
     */
    preprocessors: { './config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] },

    // Webpack Config at ./webpack.test.js
    webpack: testWebpackConfig,

    coverageReporter: {
      type: 'in-memory'
    },

    remapCoverageReporter: {
      'text-summary': null,
      json: './coverage/coverage.json',
      html: './coverage/html'
    },

    // Webpack please don't spam the console when running in karma!
    webpackMiddleware: {
      // webpack-dev-middleware configuration
      // i.e.
      noInfo: true,
      // and use stats to turn off verbose output
      stats: {
        // options i.e.
        chunks: false
      }
    },

    /*
     * test results reporter to use
     *
     * possible values: 'dots', 'progress'
     * available reporters: https://npmjs.org/browse/keyword/karma-reporter
     */
    reporters: ['mocha', 'coverage', 'remap-coverage'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    /*
     * level of logging
     * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
     */
    logLevel: config.LOG_WARN,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    /*
     * start these browsers
     * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
     */
    browsers: [
      //'Chrome'
	  'PhantomJS'
    ],

    customLaunchers: {
      ChromeTravisCi: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

	captureTimeout = 60000,
	browserDisconnectTimeout = 2000,
	browserDisconnectTolerance = 0,
	browserNoActivityTimeout = 10000,

    /*
     * Continuous Integration mode
     * if true, Karma captures browsers, runs the tests and exits
     */
    singleRun: false
  };

  if (process.env.TRAVIS) {
    configuration.browsers = [
      'ChromeTravisCi'
    ];
  }

  config.set(configuration);
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash'),
  config = require('../config'),
  chalk = require('chalk'),
  fileStreamRotator = require('file-stream-rotator'),
  fs = require('fs'),
  log4js = require('log4js');

// list of valid formats for the logging
var validFormats = ['combined', 'common', 'dev', 'short', 'tiny'];
var log4jsConfig = {
  appenders: [
    { type: 'console' },
    {
      type: 'dateFile',
      category: ['System'],
      filename: 'logs/system.log',
      pattern: '.yyyy-MM-dd',
      alwaysIncludePattern: true
    }, {
      type: 'dateFile',
      category: ['Debug'],
      filename: 'logs/debug.log',
      pattern: '.yyyy-MM-dd',
      alwaysIncludePattern: true
    }
  ],
  'replaceConsole': true
  // logger.trace('Entering cheese testing');
  // logger.debug('Got cheese.');
  // logger.info('Cheese is Gouda.');
  // logger.warn('Cheese is quite smelly.');
  // logger.error('Cheese is too ripe!');
  // logger.fatal('Cheese was breeding ground for listeria.');
};
log4js.configure({
  appenders: {
    systemLog: {
      type: 'dateFile',
      filename: 'logs/system.log',
      pattern: '.yyyy-MM-dd',
      alwaysIncludePattern: true
    },
    debugLog: {
      type: 'dateFile',
      filename: 'logs/debug.log',
      pattern: '.yyyy-MM-dd',
      alwaysIncludePattern: true
    }
  },
  categories: {
    system: { appenders: ['systemLog'], level: 'error' },
    debug: { appenders: ['debugLog'], level: 'trace' },
    console: { appenders: ['console'], level: 'trace' },
    default: { appenders: ['console', 'systemLog'], level: 'trace' }
  }
  // logger.trace('Entering cheese testing');
  // logger.debug('Got cheese.');
  // logger.info('Cheese is Gouda.');
  // logger.warn('Cheese is quite smelly.');
  // logger.error('Cheese is too ripe!');
  // logger.fatal('Cheese was breeding ground for listeria.');
});
/**
 * MORGAN LOG FORMAT
 */
function getLogFormat() {
  var format = config.log && config.log.format ? config.log.format.toString() : 'combined';

  // make sure we have a valid format
  if (!_.includes(validFormats, format)) {
    format = 'combined';

    if (process.env.NODE_ENV !== 'test') {
      console.log();
      console.log(chalk.yellow('Warning: An invalid format was provided. The logger will use the default format of "' + format + '"'));
      console.log();
    }
  }

  return format;
}

/**
 * MORGAN LOG OPTIONS
 */
function getLogOptions() {
  var options = config.log && config.log.options ? _.clone(config.log.options, true) : {};

  // check if the current environment config has the log stream option set
  if (_.has(options, 'stream')) {

    try {

      // check if we need to use rotating logs
      if (_.has(options, 'stream.rotatingLogs') && options.stream.rotatingLogs.active) {

        if (options.stream.rotatingLogs.fileName.length && options.stream.directoryPath.length) {

          // ensure the log directory exists
          if (!fs.existsSync(options.stream.directoryPath)) {
            fs.mkdirSync(options.stream.directoryPath);
          }

          options.stream = fileStreamRotator.getStream({
            filename: options.stream.directoryPath + '/' + options.stream.rotatingLogs.fileName,
            frequency: options.stream.rotatingLogs.frequency,
            verbose: options.stream.rotatingLogs.verbose
          });

        } else {
          // throw a new error so we can catch and handle it gracefully
          throw new Error('An invalid fileName or directoryPath was provided for the rotating logs option.');
        }

      } else {

        // create the WriteStream to use for the logs
        if (options.stream.fileName.length && options.stream.directoryPath.length) {

          // ensure the log directory exists
          if (!fs.existsSync(options.stream.directoryPath)) {
            fs.mkdirSync(options.stream.directoryPath);
          }

          options.stream = fs.createWriteStream(options.stream.directoryPath + '/' + config.log.options.stream.fileName, { flags: 'a' });
        } else {
          // throw a new error so we can catch and handle it gracefully
          throw new Error('An invalid fileName or directoryPath was provided for stream option.');
        }
      }
    } catch (err) {

      // remove the stream option
      delete options.stream;

      if (process.env.NODE_ENV !== 'test') {
        console.log();
        console.log(chalk.red('An error has occured during the creation of the WriteStream. The stream option has been omitted.'));
        console.log(chalk.red(err));
        console.log();
      }
    }
  }

  return options;
}

// build logger service
var logger = {
  morganLog: {
    getFormat: getLogFormat, // log format to use
    getOptions: getLogOptions // log options to use
  },
  log4jLog: {
    system: log4js.getLogger('system'),
    debug: log4js.getLogger('debug'),
    console: log4js.getLogger('console'),
  }
};

// export the logger service
module.exports = logger;
<commit_msg>Commited from lenh at Thu, Sep 28, 2017 11:51:05 AM<commit_after>'use strict';

var _ = require('lodash'),
  config = require('../config'),
  chalk = require('chalk'),
  fileStreamRotator = require('file-stream-rotator'),
  fs = require('fs'),
  log4js = require('log4js');

// list of valid formats for the logging
var validFormats = ['combined', 'common', 'dev', 'short', 'tiny'];
var log4jsConfig = {
  appenders: [
    { type: 'console' },
    {
      type: 'dateFile',
      category: ['System'],
      filename: 'logs/system.log',
      pattern: '.yyyy-MM-dd',
      alwaysIncludePattern: true
    }, {
      type: 'dateFile',
      category: ['Debug'],
      filename: 'logs/debug.log',
      pattern: '.yyyy-MM-dd',
      alwaysIncludePattern: true
    }
  ],
  'replaceConsole': true
  // logger.trace('Entering cheese testing');
  // logger.debug('Got cheese.');
  // logger.info('Cheese is Gouda.');
  // logger.warn('Cheese is quite smelly.');
  // logger.error('Cheese is too ripe!');
  // logger.fatal('Cheese was breeding ground for listeria.');
};
log4js.configure({
  appenders: {
    console: { type: 'console' },
    systemLog: {
      type: 'dateFile',
      filename: 'logs/system.log',
      pattern: '.yyyy-MM-dd',
      alwaysIncludePattern: true
    },
    debugLog: {
      type: 'dateFile',
      filename: 'logs/debug.log',
      pattern: '.yyyy-MM-dd',
      alwaysIncludePattern: true
    }
  },
  categories: {
    system: { appenders: ['systemLog'], level: 'error' },
    debug: { appenders: ['debugLog'], level: 'trace' },
    console: { appenders: ['console'], level: 'trace' },
    default: { appenders: ['console', 'systemLog'], level: 'trace' }
  }
  // logger.trace('Entering cheese testing');
  // logger.debug('Got cheese.');
  // logger.info('Cheese is Gouda.');
  // logger.warn('Cheese is quite smelly.');
  // logger.error('Cheese is too ripe!');
  // logger.fatal('Cheese was breeding ground for listeria.');
});
/**
 * MORGAN LOG FORMAT
 */
function getLogFormat() {
  var format = config.log && config.log.format ? config.log.format.toString() : 'combined';

  // make sure we have a valid format
  if (!_.includes(validFormats, format)) {
    format = 'combined';

    if (process.env.NODE_ENV !== 'test') {
      console.log();
      console.log(chalk.yellow('Warning: An invalid format was provided. The logger will use the default format of "' + format + '"'));
      console.log();
    }
  }

  return format;
}

/**
 * MORGAN LOG OPTIONS
 */
function getLogOptions() {
  var options = config.log && config.log.options ? _.clone(config.log.options, true) : {};

  // check if the current environment config has the log stream option set
  if (_.has(options, 'stream')) {

    try {

      // check if we need to use rotating logs
      if (_.has(options, 'stream.rotatingLogs') && options.stream.rotatingLogs.active) {

        if (options.stream.rotatingLogs.fileName.length && options.stream.directoryPath.length) {

          // ensure the log directory exists
          if (!fs.existsSync(options.stream.directoryPath)) {
            fs.mkdirSync(options.stream.directoryPath);
          }

          options.stream = fileStreamRotator.getStream({
            filename: options.stream.directoryPath + '/' + options.stream.rotatingLogs.fileName,
            frequency: options.stream.rotatingLogs.frequency,
            verbose: options.stream.rotatingLogs.verbose
          });

        } else {
          // throw a new error so we can catch and handle it gracefully
          throw new Error('An invalid fileName or directoryPath was provided for the rotating logs option.');
        }

      } else {

        // create the WriteStream to use for the logs
        if (options.stream.fileName.length && options.stream.directoryPath.length) {

          // ensure the log directory exists
          if (!fs.existsSync(options.stream.directoryPath)) {
            fs.mkdirSync(options.stream.directoryPath);
          }

          options.stream = fs.createWriteStream(options.stream.directoryPath + '/' + config.log.options.stream.fileName, { flags: 'a' });
        } else {
          // throw a new error so we can catch and handle it gracefully
          throw new Error('An invalid fileName or directoryPath was provided for stream option.');
        }
      }
    } catch (err) {

      // remove the stream option
      delete options.stream;

      if (process.env.NODE_ENV !== 'test') {
        console.log();
        console.log(chalk.red('An error has occured during the creation of the WriteStream. The stream option has been omitted.'));
        console.log(chalk.red(err));
        console.log();
      }
    }
  }

  return options;
}

// build logger service
var logger = {
  morganLog: {
    getFormat: getLogFormat, // log format to use
    getOptions: getLogOptions // log options to use
  },
  log4jLog: {
    system: log4js.getLogger('system'),
    debug: log4js.getLogger('debug'),
    console: log4js.getLogger('console'),
  }
};

// export the logger service
module.exports = logger;
<|endoftext|>


<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.
 */

/**
 Merge the contents of two objects together into the first object.

 ```javascript
 Ember.merge({first: 'Tom'}, {last: 'Dale'}); // {first: 'Tom', last: 'Dale'}
 var a = {first: 'Yehuda'}, b = {last: 'Katz'};
 Ember.merge(a, b); // a == {first: 'Yehuda', last: 'Katz'}, b == {last: 'Katz'}
 ```

 @method merge
 @for Ember
 @param {Object} original The object to merge into
 @param {Object} updates The object to copy properties from
 @return {Object}
 */
Ember.merge = function(original, updates) {
  for (var prop in updates) {
    if (!updates.hasOwnProperty(prop)) { continue; }
    original[prop] = updates[prop];
  }
  return original;
};

/**
 Returns true if the passed value is null or undefined. This avoids errors
 from JSLint complaining about use of ==, which can be technically
 confusing.

 ```javascript
 Ember.isNone();              // true
 Ember.isNone(null);          // true
 Ember.isNone(undefined);     // true
 Ember.isNone('');            // false
 Ember.isNone([]);            // false
 Ember.isNone(function() {});  // false
 ```

 @method isNone
 @for Ember
 @param {Object} obj Value to test
 @return {Boolean}
 */
Ember.isNone = function(obj) {
  return obj === null || obj === undefined;
};

/**
 Verifies that a value is `null` or an empty string, empty array,
 or empty function.

 Constrains the rules on `Ember.isNone` by returning false for empty
 string and empty arrays.

 ```javascript
 Ember.isEmpty();                // true
 Ember.isEmpty(null);            // true
 Ember.isEmpty(undefined);       // true
 Ember.isEmpty('');              // true
 Ember.isEmpty([]);              // true
 Ember.isEmpty('Adam Hawkins');  // false
 Ember.isEmpty([0,1,2]);         // false
 ```

 @method isEmpty
 @for Ember
 @param {Object} obj Value to test
 @return {Boolean}
 */
Ember.isEmpty = function(obj) {
  return Ember.isNone(obj) || (obj.length === 0 && typeof obj !== 'function') || (typeof obj === 'object' && Ember.get(obj, 'length') === 0);
};

/**
 A value is blank if it is empty or a whitespace string.

 ```javascript
 Ember.isBlank();                // true
 Ember.isBlank(null);            // true
 Ember.isBlank(undefined);       // true
 Ember.isBlank('');              // true
 Ember.isBlank([]);              // true
 Ember.isBlank('\n\t');          // true
 Ember.isBlank('  ');            // true
 Ember.isBlank({});              // false
 Ember.isBlank('\n\t Hello');    // false
 Ember.isBlank('Hello world');   // false
 Ember.isBlank([1,2,3]);         // false
 ```

 @method isBlank
 @for Ember
 @param {Object} obj Value to test
 @return {Boolean}
 */
Ember.isBlank = function(obj) {
  return Ember.isEmpty(obj) || (typeof obj === 'string' && obj.match(/\S/) === null);
};

/**
 * Calculates sum of two numbers
 * Use this function as a callback on invoke etc
 *
 * @method sum
 * @param {Number} a
 * @param {Number} b
 * @returns {Number}
 */
Ember.sum = function (a, b) {
  return a + b;
};

/**
 * Execute passed callback
 *
 * @param {Function} callback
 * @returns {*}
 */
Ember.clb = function (callback) {
  return callback();
};

/**
 *
 */
Ember.RadioButton = Ember.Checkbox.extend({
  tagName: "input",
  type: "radio",
  attributeBindings: [ "type", "name", "value", "checked", "style", "disabled" ],
  click: function () {
    this.set("selection", this.$().val())
  },
  checked: function () {
    return this.get("value") === this.get("selection");
  }.property('value', 'selection')
});

/**
 * Set value to obj by path
 * Create nested objects if needed
 * Example:
 *
 *   var a = {b: {}};
 *   var path = 'b.c.d';
 *   var value = 1;
 *   Em.setFullPath(a, path, value); // a = {b: {c: {d: 1}}}
 *
 *
 * @param {object} obj
 * @param {string} path
 * @param {*} value
 */
Ember.setFullPath = function (obj, path, value) {
  var parts = path.split('.'),
    sub_path = '';
  parts.forEach(function(_path, _index) {
    Em.assert('path parts can\'t be empty', _path.length);
    sub_path += '.' + _path;
    if (_index === parts.length - 1) {
      Em.set(obj, sub_path, value);
      return;
    }
    if (Em.isNone(Em.get(obj, sub_path))) {
      Em.set(obj, sub_path, {});
    }
  });
};

/**
 *
 * @param {object} target
 * @param {string[]} propertyNames
 * @returns {{}}
 */
Ember.getProperties = function (target, propertyNames) {
  var ret = {};
  for(var i = 0; i < propertyNames.length; i++) {
    ret[propertyNames[i]] = Em.get(target, propertyNames[i]);
  }
  return ret;
};

Em.View.reopen({
  /**
   * overwritten set method of Ember.View to avoid uncaught errors
   * when trying to set property of destroyed view
   */
  set: function(attr, value){
    if(!this.get('isDestroyed') && !this.get('isDestroying')){
      this._super(attr, value);
    } else {
      console.debug('Calling set on destroyed view');
    }
  },

  /**
   * overwritten setProperties method of Ember.View to avoid uncaught errors
   * when trying to set multiple properties of destroyed view
   */
  setProperties: function(hash){
    if(!this.get('isDestroyed') && !this.get('isDestroying')){
      this._super(hash);
    } else {
      console.debug('Calling setProperties on destroyed view');
    }
  }
});

Ember._HandlebarsBoundView.reopen({
  /**
   * overwritten set method of Ember._HandlebarsBoundView to avoid uncaught errors
   * when trying to set property of destroyed view
   */
  render: function(buffer){
    if(!this.get('isDestroyed') && !this.get('isDestroying')){
      this._super(buffer);
    } else {
      console.debug('Calling render on destroyed view');
    }
  }
});

Ember.TextArea.reopen({
  attributeBindings: ['readonly']
});

/**
 * Simply converts query string to object.
 *
 * @param  {string} queryString query string e.g. '?param1=value1&param2=value2'
 * @return {object} converted object
 */
function parseQueryParams(queryString) {
  if (!queryString) {
    return {};
  }
  return queryString.replace(/^\?/, '').split('&').map(decodeURIComponent)
    .reduce(function(p, c) {
      var keyVal = c.split('=');
      p[keyVal[0]] = keyVal[1];
      return p;
    }, {});
};

Ember.Route.reopen({
  /**
   *  When you move to a new route by pressing the back or forward button, change url manually, click on link with url defined in href,
   *  call Router.transitionTo or Router.route this method is called.
   *  This method unites unroutePath, navigateAway and exit events to handle Route leaving in one place.
   *  Also unlike the exit event it is possible to stop transition inside this handler.
   *  To proceed transition just call callback..
   *
   * @param {Router}  router
   * @param {Object|String} context context from transition or path from route
   * @param {callback} callback should be called to proceed transition
   */
  exitRoute: function (router, context, callback) {
    callback();
  },

  /**
   * Query Params serializer. This method should be used inside serialize method.
   * You need to specify `:query` dynamic sygment in your route's route attribute
   * e.g. Em.Route.extend({ route: '/login:query'}) and return result of this method.
   * This method will set serializedQuery property to specified controller by name.
   * For concrete example see `app/routes/main.js`.
   *
   * @example
   *  queryParams: Em.Route.extend({
   *   route: '/queryDemo:query',
   *   serialize: function(route, params) {
   *     return this.serializeQueryParams(route, params, 'controllerNameToSetQueryObject');
   *   }
   *  });
   *  // now when navigated to http://example.com/#/queryDemo?param1=value1&param2=value2
   *  // App.router.get('controllerNameToSetQueryObject').get('serializedQuery')
   *  // will return { param1: 'value1', param2: 'value2' }
   *
   * @param  {Em.Router} router router instance passed to serialize method
   * @param  {object} params dynamic segment passed to seriazlie
   * @param  {string} controllerName name of the controller to set `serializedQuery` as result
   * @return {object}
   */
  serializeQueryParams: function(router, params, controllerName) {
    var controller = router.get(controllerName);
    controller.set('serializedQuery', parseQueryParams(params ? params.query : ''));
    return params || { query: ''};
  },

  scrollTop() {
    window.scrollTo(0, 0);
  }

});

Ember.Router.reopen({

  // reopen original transitionTo and route methods to add calling of exitRoute

  transitionTo: function (router, context) {
    var self = this;
    var args = arguments;
    var transitionTo = self._super;
    var callback = function () {
      transitionTo.apply(self, args);
    };
    if (!this.get('currentState.exitRoute')) {
      callback();
    } else {
      this.get('currentState').exitRoute(this, context, callback);
    }
  },

  route: function (path) {
    var self = this;
    var args = arguments;
    var transitionTo = self._super;
    var callback = function () {
      self.get('location').setURL(path);
      transitionTo.apply(self, args);
    };
    var realPath;
    if (!this.get('currentState.exitRoute')) {
      callback();
    } else {
      realPath = this.get('currentState').absoluteRoute(this);
      this.get('location').setURL(realPath);
      this.get('currentState').exitRoute(this, path, callback);
    }
  }
});
<commit_msg>AMBARI-20099.Password fields are not disabled when should be (onechiporenko)<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.
 */

/**
 Merge the contents of two objects together into the first object.

 ```javascript
 Ember.merge({first: 'Tom'}, {last: 'Dale'}); // {first: 'Tom', last: 'Dale'}
 var a = {first: 'Yehuda'}, b = {last: 'Katz'};
 Ember.merge(a, b); // a == {first: 'Yehuda', last: 'Katz'}, b == {last: 'Katz'}
 ```

 @method merge
 @for Ember
 @param {Object} original The object to merge into
 @param {Object} updates The object to copy properties from
 @return {Object}
 */
Ember.merge = function(original, updates) {
  for (var prop in updates) {
    if (!updates.hasOwnProperty(prop)) { continue; }
    original[prop] = updates[prop];
  }
  return original;
};

/**
 Returns true if the passed value is null or undefined. This avoids errors
 from JSLint complaining about use of ==, which can be technically
 confusing.

 ```javascript
 Ember.isNone();              // true
 Ember.isNone(null);          // true
 Ember.isNone(undefined);     // true
 Ember.isNone('');            // false
 Ember.isNone([]);            // false
 Ember.isNone(function() {});  // false
 ```

 @method isNone
 @for Ember
 @param {Object} obj Value to test
 @return {Boolean}
 */
Ember.isNone = function(obj) {
  return obj === null || obj === undefined;
};

/**
 Verifies that a value is `null` or an empty string, empty array,
 or empty function.

 Constrains the rules on `Ember.isNone` by returning false for empty
 string and empty arrays.

 ```javascript
 Ember.isEmpty();                // true
 Ember.isEmpty(null);            // true
 Ember.isEmpty(undefined);       // true
 Ember.isEmpty('');              // true
 Ember.isEmpty([]);              // true
 Ember.isEmpty('Adam Hawkins');  // false
 Ember.isEmpty([0,1,2]);         // false
 ```

 @method isEmpty
 @for Ember
 @param {Object} obj Value to test
 @return {Boolean}
 */
Ember.isEmpty = function(obj) {
  return Ember.isNone(obj) || (obj.length === 0 && typeof obj !== 'function') || (typeof obj === 'object' && Ember.get(obj, 'length') === 0);
};

/**
 A value is blank if it is empty or a whitespace string.

 ```javascript
 Ember.isBlank();                // true
 Ember.isBlank(null);            // true
 Ember.isBlank(undefined);       // true
 Ember.isBlank('');              // true
 Ember.isBlank([]);              // true
 Ember.isBlank('\n\t');          // true
 Ember.isBlank('  ');            // true
 Ember.isBlank({});              // false
 Ember.isBlank('\n\t Hello');    // false
 Ember.isBlank('Hello world');   // false
 Ember.isBlank([1,2,3]);         // false
 ```

 @method isBlank
 @for Ember
 @param {Object} obj Value to test
 @return {Boolean}
 */
Ember.isBlank = function(obj) {
  return Ember.isEmpty(obj) || (typeof obj === 'string' && obj.match(/\S/) === null);
};

/**
 * Calculates sum of two numbers
 * Use this function as a callback on invoke etc
 *
 * @method sum
 * @param {Number} a
 * @param {Number} b
 * @returns {Number}
 */
Ember.sum = function (a, b) {
  return a + b;
};

/**
 * Execute passed callback
 *
 * @param {Function} callback
 * @returns {*}
 */
Ember.clb = function (callback) {
  return callback();
};

/**
 *
 */
Ember.RadioButton = Ember.Checkbox.extend({
  tagName: "input",
  type: "radio",
  attributeBindings: [ "type", "name", "value", "checked", "style", "disabled" ],
  click: function () {
    this.set("selection", this.$().val())
  },
  checked: function () {
    return this.get("value") === this.get("selection");
  }.property('value', 'selection')
});

/**
 * Set value to obj by path
 * Create nested objects if needed
 * Example:
 *
 *   var a = {b: {}};
 *   var path = 'b.c.d';
 *   var value = 1;
 *   Em.setFullPath(a, path, value); // a = {b: {c: {d: 1}}}
 *
 *
 * @param {object} obj
 * @param {string} path
 * @param {*} value
 */
Ember.setFullPath = function (obj, path, value) {
  var parts = path.split('.'),
    sub_path = '';
  parts.forEach(function(_path, _index) {
    Em.assert('path parts can\'t be empty', _path.length);
    sub_path += '.' + _path;
    if (_index === parts.length - 1) {
      Em.set(obj, sub_path, value);
      return;
    }
    if (Em.isNone(Em.get(obj, sub_path))) {
      Em.set(obj, sub_path, {});
    }
  });
};

/**
 *
 * @param {object} target
 * @param {string[]} propertyNames
 * @returns {{}}
 */
Ember.getProperties = function (target, propertyNames) {
  var ret = {};
  for(var i = 0; i < propertyNames.length; i++) {
    ret[propertyNames[i]] = Em.get(target, propertyNames[i]);
  }
  return ret;
};

Em.View.reopen({
  /**
   * overwritten set method of Ember.View to avoid uncaught errors
   * when trying to set property of destroyed view
   */
  set: function(attr, value){
    if(!this.get('isDestroyed') && !this.get('isDestroying')){
      this._super(attr, value);
    } else {
      console.debug('Calling set on destroyed view');
    }
  },

  /**
   * overwritten setProperties method of Ember.View to avoid uncaught errors
   * when trying to set multiple properties of destroyed view
   */
  setProperties: function(hash){
    if(!this.get('isDestroyed') && !this.get('isDestroying')){
      this._super(hash);
    } else {
      console.debug('Calling setProperties on destroyed view');
    }
  }
});

Ember._HandlebarsBoundView.reopen({
  /**
   * overwritten set method of Ember._HandlebarsBoundView to avoid uncaught errors
   * when trying to set property of destroyed view
   */
  render: function(buffer){
    if(!this.get('isDestroyed') && !this.get('isDestroying')){
      this._super(buffer);
    } else {
      console.debug('Calling render on destroyed view');
    }
  }
});

Ember.TextField.reopen({
  attributeBindings: ['readOnly']
});

Ember.TextArea.reopen({
  attributeBindings: ['readonly']
});

/**
 * Simply converts query string to object.
 *
 * @param  {string} queryString query string e.g. '?param1=value1&param2=value2'
 * @return {object} converted object
 */
function parseQueryParams(queryString) {
  if (!queryString) {
    return {};
  }
  return queryString.replace(/^\?/, '').split('&').map(decodeURIComponent)
    .reduce(function(p, c) {
      var keyVal = c.split('=');
      p[keyVal[0]] = keyVal[1];
      return p;
    }, {});
};

Ember.Route.reopen({
  /**
   *  When you move to a new route by pressing the back or forward button, change url manually, click on link with url defined in href,
   *  call Router.transitionTo or Router.route this method is called.
   *  This method unites unroutePath, navigateAway and exit events to handle Route leaving in one place.
   *  Also unlike the exit event it is possible to stop transition inside this handler.
   *  To proceed transition just call callback..
   *
   * @param {Router}  router
   * @param {Object|String} context context from transition or path from route
   * @param {callback} callback should be called to proceed transition
   */
  exitRoute: function (router, context, callback) {
    callback();
  },

  /**
   * Query Params serializer. This method should be used inside serialize method.
   * You need to specify `:query` dynamic sygment in your route's route attribute
   * e.g. Em.Route.extend({ route: '/login:query'}) and return result of this method.
   * This method will set serializedQuery property to specified controller by name.
   * For concrete example see `app/routes/main.js`.
   *
   * @example
   *  queryParams: Em.Route.extend({
   *   route: '/queryDemo:query',
   *   serialize: function(route, params) {
   *     return this.serializeQueryParams(route, params, 'controllerNameToSetQueryObject');
   *   }
   *  });
   *  // now when navigated to http://example.com/#/queryDemo?param1=value1&param2=value2
   *  // App.router.get('controllerNameToSetQueryObject').get('serializedQuery')
   *  // will return { param1: 'value1', param2: 'value2' }
   *
   * @param  {Em.Router} router router instance passed to serialize method
   * @param  {object} params dynamic segment passed to seriazlie
   * @param  {string} controllerName name of the controller to set `serializedQuery` as result
   * @return {object}
   */
  serializeQueryParams: function(router, params, controllerName) {
    var controller = router.get(controllerName);
    controller.set('serializedQuery', parseQueryParams(params ? params.query : ''));
    return params || { query: ''};
  },

  scrollTop() {
    window.scrollTo(0, 0);
  }

});

Ember.Router.reopen({

  // reopen original transitionTo and route methods to add calling of exitRoute

  transitionTo: function (router, context) {
    var self = this;
    var args = arguments;
    var transitionTo = self._super;
    var callback = function () {
      transitionTo.apply(self, args);
    };
    if (!this.get('currentState.exitRoute')) {
      callback();
    } else {
      this.get('currentState').exitRoute(this, context, callback);
    }
  },

  route: function (path) {
    var self = this;
    var args = arguments;
    var transitionTo = self._super;
    var callback = function () {
      self.get('location').setURL(path);
      transitionTo.apply(self, args);
    };
    var realPath;
    if (!this.get('currentState.exitRoute')) {
      callback();
    } else {
      realPath = this.get('currentState').absoluteRoute(this);
      this.get('location').setURL(realPath);
      this.get('currentState').exitRoute(this, path, callback);
    }
  }
});
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * Gets the current guild and member counts.
 *
 * @param {CommandoClient} client - The Discord.JS-Commando Client object
 * @returns {object} - An object containing two properties, guilds and members, each representing the associated counts.
 */
exports.getGuildsAndMembers = client => {
	return client.guilds.reduce((acc, guild) => {
		console.log(acc);
		acc.guilds  += 1;
		acc.members += guild.members.array().length;
		return acc;
	}, {
		guilds:  0,
		members: 0,
	});
};

exports.setGame = client => {
	let { guilds, members } = this.getGuildsAndMembers(client);
	client.user.setGame(`${client.commandPrefix || client.options.commandPrefix}help | Serving ${members} members across ${guilds} guilds`);
};
<commit_msg>Remove my debugging statement... again<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * Gets the current guild and member counts.
 *
 * @param {CommandoClient} client - The Discord.JS-Commando Client object
 * @returns {object} - An object containing two properties, guilds and members, each representing the associated counts.
 */
exports.getGuildsAndMembers = client => {
	return client.guilds.reduce((acc, guild) => {
		acc.guilds  += 1;
		acc.members += guild.members.array().length;
		return acc;
	}, {
		guilds:  0,
		members: 0,
	});
};

exports.setGame = client => {
	let { guilds, members } = this.getGuildsAndMembers(client);
	client.user.setGame(`${client.commandPrefix || client.options.commandPrefix}help | Serving ${members} members across ${guilds} guilds`);
};
<|endoftext|>