<commit_before>core.RegisterLoadingProcess("photobrowser", function(){

	if ( !core.onPage("/home") ) return

	document.getElementsByClassName("photobrowser").forEach(function(photobrowser) {

		photobrowser.getElementsByClassName("scrollbar").forEach(function(scrollbar) {
			scrollbar.style.display = "none"
		})

		var thumbnail_holder = document.getElementByClassName("bc_thumbs")
		if ( !thumbnail_holder ) {
			thumbnail_holder = document.createElement("div")
			thumbnail_holder.addClass("bc_thumbs")
			thumbnail_holder.setStyle("position: absolute; left: 20px; right: 210px; top: 30px")
			thumbnail_holder.appendTo(photobrowser)
		}

		photobrowser.getElementsByClassName("thumbnails").forEach(function(thumbs) {
			thumbs.style.display = "none"
			thumbs.getElementsByTagName("li").forEach(function(item) {
				core.ProcessElement(item, function() {
					var image = this.getElementByTagName("img")

					var url = ""
					var src = image ? image.src : ""
					var user = (/^[^_]+_(.+)$/).match(item.id, 1) || ""

					var detail = document.getElementById("browser_"+user)
					if ( detail ) {
						detail.setAttribute("data-bc-user", user)
						var username = detail.getElementByClassName("username")
						if ( username ) {
							var anchor = username.getElementByTagName("a")
							if ( anchor ) {
								url = anchor.href
							}
						}
					}

					var a = document.createElement("a")
					a.href = url

					var img = document.createElement("img")
					img.src = src
					img.setAttribute("data-bc-user", user)
					img.setStyle("width: 79px; height: 79px; margin: 0 8px 8px 0")

					img.addEventListener("mouseover", function(e) {
						var $detail = $(document.getElementById("browser_"+this.getAttribute("data-bc-user")))
						$detail.siblings().clearQueue().stop().animate({
							opacity: 0,
						}, {
							duration: 'slow',
							complete: function() {
								this.style.display = 'none'
							}
						})
						$detail.clearQueue().stop().css('display', 'block').animate({
							opacity: 1
						}, 'fast')
					}, false)

					img.appendTo(a)
					a.appendTo(thumbnail_holder)
				})
			})
		})

		photobrowser.getElementsByClassName("items").forEach(function(items) {

			core.ProcessElement(items, function() {
				this.setStyle({
					position: "relative",
					margin: "0px",
					height: "216px",
					width: "100%"
				})
			})

			items.getElementsByClassName("item").forEach(function(item, i) {

				core.ProcessElement(item, function() {
					this.setStyle({
						display: i == 0 ? "block" : "none",
						height: "190px",
						position: "absolute",
						right: parseInt(this.style.marginRight) > 0 ? "0px" : "6px"
					})

					var user = this.getAttribute("data-bc-user")
					var js_params = "'"+user+"', 'divname', 'match/reject_result.html', '"+i+"'"

					var hide_button = document.createElement("p")
					hide_button.id = "hide_btn_"+i
					hide_button.addClass("btn white button small active")
					hide_button.setStyle("margin: 0px auto")
					hide_button.innerHTML = "hide"

					var unhide_button = document.createElement("p")
					unhide_button.id = "unhide_btn_"+i
					unhide_button.addClass("btn white button small active unhider")
					unhide_button.setStyle("margin: 0px auto; display: none")
					unhide_button.innerHTML = "un-hide"

					var info = this.getElementsByClassName("info")[0]
					info.appendChild(hide_button)
					info.appendChild(unhide_button)
				})

			})

		})

	})

	var matches_block = document.getElementById("matches_block")
	if ( matches_block ) {
		var links = matches_block.getElementByClassName("links")
		if ( links ) {

			var improve = links.querySelector("li.improve")
			core.ProcessElement(improve, function() {
				this.setStyle({
					bottom: "14px",
					left: "30px"
				})
			})

			var more = links.querySelector("li.more")
			core.ProcessElement(more, function() {
				this.setStyle({
					bottom: "14px",
					right: "235px"
				})
			})

		}
	}

})<commit_msg>Bugfix: The photobrowser detail image on the homepage should no longer shift on the last element.<commit_after>core.RegisterLoadingProcess("photobrowser", function(){

	if ( !core.onPage("/home") ) return

	document.getElementsByClassName("photobrowser").forEach(function(photobrowser) {

		photobrowser.getElementsByClassName("scrollbar").forEach(function(scrollbar) {
			scrollbar.style.display = "none"
		})

		var thumbnail_holder = document.getElementByClassName("bc_thumbs")
		if ( !thumbnail_holder ) {
			thumbnail_holder = document.createElement("div")
			thumbnail_holder.addClass("bc_thumbs")
			thumbnail_holder.setStyle("position: absolute; left: 20px; right: 210px; top: 30px")
			thumbnail_holder.appendTo(photobrowser)
		}

		photobrowser.getElementsByClassName("thumbnails").forEach(function(thumbs) {
			thumbs.style.display = "none"
			thumbs.getElementsByTagName("li").forEach(function(item) {
				core.ProcessElement(item, function() {
					var image = this.getElementByTagName("img")

					var url = ""
					var src = image ? image.src : ""
					var user = (/^[^_]+_(.+)$/).match(item.id, 1) || ""

					var detail = document.getElementById("browser_"+user)
					if ( detail ) {
						detail.setAttribute("data-bc-user", user)
						var username = detail.getElementByClassName("username")
						if ( username ) {
							var anchor = username.getElementByTagName("a")
							if ( anchor ) {
								url = anchor.href
							}
						}
					}

					var a = document.createElement("a")
					a.href = url

					var img = document.createElement("img")
					img.src = src
					img.setAttribute("data-bc-user", user)
					img.setStyle("width: 79px; height: 79px; margin: 0 8px 8px 0")

					img.addEventListener("mouseover", function(e) {
						var $detail = $(document.getElementById("browser_"+this.getAttribute("data-bc-user")))
						$detail.siblings().clearQueue().stop().animate({
							opacity: 0,
						}, {
							duration: 'slow',
							complete: function() {
								this.style.display = 'none'
							}
						})
						$detail.clearQueue().stop().css('display', 'block').animate({
							opacity: 1
						}, 'fast')
					}, false)

					img.appendTo(a)
					a.appendTo(thumbnail_holder)
				})
			})
		})

		photobrowser.getElementsByClassName("items").forEach(function(items) {

			core.ProcessElement(items, function() {
				this.setStyle({
					position: "relative",
					margin: "0px",
					height: "216px",
					width: "100%"
				})
			})

			items.getElementsByClassName("item").forEach(function(item, i, arr) {

				item.style.right = i === arr.length - 1 ? "6px" : "0px";

				core.ProcessElement(item, function() {
					this.setStyle({
						display: i == 0 ? "block" : "none",
						height: "190px",
						position: "absolute"
					})

					var user = this.getAttribute("data-bc-user")
					var js_params = "'"+user+"', 'divname', 'match/reject_result.html', '"+i+"'"

					var hide_button = document.createElement("p")
					hide_button.id = "hide_btn_"+i
					hide_button.addClass("btn white button small active")
					hide_button.setStyle("margin: 0px auto")
					hide_button.innerHTML = "hide"

					var unhide_button = document.createElement("p")
					unhide_button.id = "unhide_btn_"+i
					unhide_button.addClass("btn white button small active unhider")
					unhide_button.setStyle("margin: 0px auto; display: none")
					unhide_button.innerHTML = "un-hide"

					var info = this.getElementsByClassName("info")[0]
					info.appendChild(hide_button)
					info.appendChild(unhide_button)
				})

			})

		})

	})

	var matches_block = document.getElementById("matches_block")
	if ( matches_block ) {
		var links = matches_block.getElementByClassName("links")
		if ( links ) {

			var improve = links.querySelector("li.improve")
			core.ProcessElement(improve, function() {
				this.setStyle({
					bottom: "14px",
					left: "30px"
				})
			})

			var more = links.querySelector("li.more")
			core.ProcessElement(more, function() {
				this.setStyle({
					bottom: "14px",
					right: "235px"
				})
			})

		}
	}

})<|endoftext|>


<commit_before>'use strict';

navigator.getUserMedia = navigator.getUserMedia ||
    navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

var constraints = {
  audio: false,
  video: true
};
var video = document.querySelector('video');

function successCallback(stream) {
  window.stream = stream; // stream available to console
  if (window.URL) {
    video.src = window.URL.createObjectURL(stream);
  } else {
    video.src = stream;
  }
}

function errorCallback(error) {
  console.log('navigator.getUserMedia error: ', error);
}

navigator.getUserMedia(constraints, successCallback, errorCallback);
<commit_msg>Updated gum<commit_after>'use strict';

navigator.getUserMedia = navigator.getUserMedia ||
    navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

var constraints = {
  video: true
};

var video = document.querySelector('video');

function handleSuccess(stream) {
  window.stream = stream; // stream available to console
  video.src = window.URL.createObjectURL(stream);
}

function handleError(error) {
  console.log('navigator.getUserMedia error: ', error);
}

navigator.mediaDevices.getUserMedia(constraints).
    then(handleSuccess).catch(handleError);
<|endoftext|>


<commit_before>$(document).ready(function(){

    /**
     * The elements that should be in the mega-menu
     */

    var megaMenuItems = [
        { 'title': 'Site Foundation', 'items': [
                { 'title': 'Site Header', 'url': 'element_site_header.html' },
                { 'title': 'Site Layouts', 'url': 'pattern_site_layouts.html' },
                { 'title': 'Grids', 'url': 'pattern_grids.html' },
                { 'title': 'Colors', 'url': 'foundation_colors.html' },
                { 'title': 'Text', 'url': 'foundation_text.html' }
        ]},
        { 'title': 'Page Elements', 'items': [
                { 'title': 'Messages', 'url': 'element_messages.html' },
                { 'title': 'Buttons', 'url': 'element_buttons.html' },
                { 'title': 'Badges', 'url': 'element_badges.html' },
                { 'title': 'Navigation', 'url': 'element_navigation.html' },
                { 'title': 'Forms', 'url': 'element_form.html' },
                { 'title': 'Blockquotes', 'url': 'element_blockquotes.html' },
                { 'title': 'Lists', 'url': 'element_lists.html' },
                { 'title': 'Tables', 'url': 'element_tables.html' }
        ]},
        { 'title': 'Content Patterns', 'items': [
                { 'title': 'Site Layouts', 'url': 'pattern_site_layouts.html' },
                { 'title': 'Grouping Text', 'url': 'pattern_text.html' },
                { 'title': 'Quicklinks Box', 'url': 'pattern_quicklinks.html' },
                { 'title': 'Tabbed Sections', 'url': 'pattern_tabs.html' },
                { 'title': 'Frequently Asked Questions', 'url': 'pattern_faq.html' },
                { 'title': 'News & Events List', 'url': 'pattern_news_events_list.html' }
        ]}
    ];

    /**
     * Populate the mega-menu per megaMenuItems
     */
    var $ul = $(document.createElement('ul'));
    $.each(megaMenuItems, function(){
        var $li = $(document.createElement('li')),
            $header = $(document.createElement(this.items ? 'h1' : 'span')),
            $a = $(document.createElement('a')).html(this.title);

        if(this.url)
            $a.attr('href',this.url);

        $li.append($header.append($a));

        if(this.items){
            var $inner_ul = $(document.createElement('ul'));
            $.each(this.items, function(){
                var $inner_li = $(document.createElement('li')),
                    $inner_a = $(document.createElement('a')).attr('href', this.url).html(this.title)

                if(this.subtitle){
                    $inner_a.append('
'+this.subtitle+'')
                }
                $inner_ul.append($inner_li.append($inner_a));
            });
            $li.append($inner_ul);
        }

        $ul.append($li);
    })
    $('header.site:not(main header) nav.mega').append($ul);

    WebBlocks.navMegaMenu.call($('header.site'));

    $('head').append('<link rel="stylesheet" href="_core/styles.css">')
             .append('')
             .append('')
             .append('<link rel="stylesheet" href="_core/prettify/prettify.css">');

    prettyPrint();

})<commit_msg>Add content grids to the patterns megamenu section<commit_after>$(document).ready(function(){

    /**
     * The elements that should be in the mega-menu
     */

    var megaMenuItems = [
        { 'title': 'Site Foundation', 'items': [
                { 'title': 'Site Header', 'url': 'element_site_header.html' },
                { 'title': 'Site Layouts', 'url': 'pattern_site_layouts.html' },
                { 'title': 'Content Grids', 'url': 'pattern_grids.html' },
                { 'title': 'Colors', 'url': 'foundation_colors.html' },
                { 'title': 'Text', 'url': 'foundation_text.html' }
        ]},
        { 'title': 'Page Elements', 'items': [
                { 'title': 'Messages', 'url': 'element_messages.html' },
                { 'title': 'Buttons', 'url': 'element_buttons.html' },
                { 'title': 'Badges', 'url': 'element_badges.html' },
                { 'title': 'Navigation', 'url': 'element_navigation.html' },
                { 'title': 'Forms', 'url': 'element_form.html' },
                { 'title': 'Blockquotes', 'url': 'element_blockquotes.html' },
                { 'title': 'Lists', 'url': 'element_lists.html' },
                { 'title': 'Tables', 'url': 'element_tables.html' }
        ]},
        { 'title': 'Content Patterns', 'items': [
                { 'title': 'Site Layouts', 'url': 'pattern_site_layouts.html' },
                { 'title': 'Content Grids', 'url': 'pattern_grids.html' },
                { 'title': 'Grouping Text', 'url': 'pattern_text.html' },
                { 'title': 'Quicklinks Box', 'url': 'pattern_quicklinks.html' },
                { 'title': 'Tabbed Sections', 'url': 'pattern_tabs.html' },
                { 'title': 'Frequently Asked Questions', 'url': 'pattern_faq.html' },
                { 'title': 'News & Events List', 'url': 'pattern_news_events_list.html' }
        ]}
    ];

    /**
     * Populate the mega-menu per megaMenuItems
     */
    var $ul = $(document.createElement('ul'));
    $.each(megaMenuItems, function(){
        var $li = $(document.createElement('li')),
            $header = $(document.createElement(this.items ? 'h1' : 'span')),
            $a = $(document.createElement('a')).html(this.title);

        if(this.url)
            $a.attr('href',this.url);

        $li.append($header.append($a));

        if(this.items){
            var $inner_ul = $(document.createElement('ul'));
            $.each(this.items, function(){
                var $inner_li = $(document.createElement('li')),
                    $inner_a = $(document.createElement('a')).attr('href', this.url).html(this.title)

                if(this.subtitle){
                    $inner_a.append('
'+this.subtitle+'')
                }
                $inner_ul.append($inner_li.append($inner_a));
            });
            $li.append($inner_ul);
        }

        $ul.append($li);
    })
    $('header.site:not(main header) nav.mega').append($ul);

    WebBlocks.navMegaMenu.call($('header.site'));

    $('head').append('<link rel="stylesheet" href="_core/styles.css">')
             .append('')
             .append('')
             .append('<link rel="stylesheet" href="_core/prettify/prettify.css">');

    prettyPrint();

})<|endoftext|>


<commit_before>/*
 * grunt-bbb-requirejs
 * http://gruntjs.com/
 *
 * Copyright (c) 2013 Tim Branyen, Tyler Kellen, contributors
 * Licensed under the MIT license.
 */
"use strict";

module.exports = function(grunt) {
  var ENV = process.env;
  var CWD = process.cwd();

  var fs = require("fs");
  var path = require("path");
  var requirejs = require("requirejs");
  var _ = grunt.util._;
  var log = grunt.log;

  // Convert the contents passed to CommonJS and then return.
  function toCommonJS(moduleName, contents, commonJs) {
    return commonJs.convert(moduleName, String(contents));
  }

  // TODO: extend this to send build log to grunt.log.ok / grunt.log.error by
  // overriding the r.js logger (or submit issue to r.js to expand logging
  // support)
  requirejs.define("node/print", [], function() {
    return function print(msg) {
      if (msg.substring(0, 5) === "Error") {
        grunt.log.errorlns(msg);
        grunt.fail.warn("RequireJS failed.");
      } else {
        grunt.log.oklns(msg);
      }
    };
  });

  grunt.registerTask("list", "Show module dependencies.", function(prop) {
    var options = grunt.config("requirejs") || {};
    var baseUrl = options.baseUrl || "app";
    var done = this.async();
    var exports = {};

    exports.init = function(grunt) {
      var exports = {};
      var _ = grunt.util._;

      exports.list = function(appDir, done) {
        var jsRegExp = /\.js$/;

        requirejs.tools.useLib(function(require) {
          require(["parse", "commonJs"], function(parse, commonJs) {
            var deps = {};
            var files = [];

            // Recursively find all files inside the application directory
            function recurse(dir) {
              fs.readdirSync(dir).forEach(function(name) {
                var subdir = path.resolve(dir, name);
                var stats = fs.statSync(subdir);

                if (stats.isDirectory()) {
                  recurse(subdir);
                } else if (jsRegExp.test(name)) {
                  files.push(subdir);
                }
              });
            }

            // Start with the app directory e.g. app/
            recurse(appDir);

            files.forEach(function(name) {
              var contents = fs.readFileSync(name, "utf8");
              var shortname = name.slice(name.indexOf(appDir));
              var dep, all;

              // Convert to CommonJS first.
              contents = commonJs.convert(name, contents);

              try {
                dep = parse.findDependencies(name, contents)
              } catch (ex) {
                console.log(ex);
              }

              if (dep && dep.length) {
                all = deps[shortname] = parse.findDependencies(name, contents);

                // Remove `require`, `module`, `exports`.
                all.splice(all.indexOf("require"), 1);
                all.splice(all.indexOf("module"), 1);
                all.splice(all.indexOf("exports"), 1);
              }
            });

            console.log(exports.tree(deps));
            done();
          });
        });
      };

      exports.tree = function(obj) {
        var tree = [""];

        function spaces(len, end, start) {
          start = start || " ";
          end = end || " ";

          if (!start) {
            return Array(len+1).join(Array(3).join(end));
          } else {
            return Array(len+1).join(start + Array(2).join(end));
          }
        }

        function traverse(obj, depth) {
          _.each(obj, function(val, key) {
            var len;

            if (_.isArray(val)) {
              tree.push("\u251c" + spaces(depth) + " " + key);

              len = val.length;

              _.each(val, function(val, i) {
                if (_.isString(val)) {
                  if (i == len-1) {
                    tree.push("\u2502 " + spaces(depth+1, "\u2500", "\u2514") + " "
                      + val);
                  } else {
                    tree.push("\u2502 " + spaces(depth+1, "\u2500", "\u251c") + " "
                      + val);
                  }
                } else if (_.isObject(val)) {
                  traverse(obj, depth+1);
                }
              });

              tree.push("\u2502");

            } else if (_.isObject(val)) {
              tree.push(spaces(depth) + key);
              traverse(val, depth+1);
            } else {
              tree.push(spaces(depth) + key);
            }

          });
        }

        traverse(obj, 0);

        tree.pop();

        return tree.join("\n");
      };

      return exports;
    };

    exports.init(grunt).list(path.normalize(baseUrl + "/"), done);
  });

  grunt.registerMultiTask("requirejs", "Build with r.js.", function() {
    // Make the current task reusable within the async callbacks below.
    var task = this;

    // Put this task into `async-mode`, cause we're gonna need it.
    var done = task.async();

    // Cache this function so that we can reuse it within RequireJS's
    // utilities.
    var nodeRequire = require;

    // Access RequireJS's internal utilities.
    requirejs.tools.useLib(function(require) {
      // Get access to the CommonJS convert utility.
      require(["commonJs"], function(commonJs) {
        var options = task.options({
          // Include the main ration file.
          mainConfigFile: "app/config.js",

          // Setting the base url to the distribution directory allows the
          // Uglify minification process to correctly map paths for Source
          // Maps.
          baseUrl: "dist/app",

          // Default location for where scripts are modules.
          moduleDirs: ["dist/app", "dist/test"],

          // Include Almond to slim down the built filesize.
          name: "almond",

          // Set the Bootstrap as the main entry point.
          include: ["main"],
          insertRequire: ["main"],

          // Since we bootstrap with nested `require` calls this option allows
          // R.js to find them.
          findNestedDependencies: true,

          // Wrap everything in an IIFE.
          wrap: true,

          // Output file.
          out: "dist/source.min.js",

          // Enable Source Map generation.
          generateSourceMaps: true,

          // Do not preserve any license comments when working with source maps.
          // These options are incompatible.
          preserveLicenseComments: false,

          // Minify using UglifyJS.
          optimize: "uglify2",

          // Show warnings
          logLevel: 2,

          // Ensure modules are inserted
          skipModuleInsertion: false,

          // If the contents do not contain a define call, then wrap with
          onBuildRead: function (moduleName, filePath, contents) {
            var moduleDir = _.find(options.moduleDirs, function(dir) {
              return filePath.indexOf(path.resolve(CWD, dir)) === 0;
            });

            // Do not execute the conversion on files that do not exist in the
            // main application path.
            if (!moduleDir) {
              return contents;
            }

            // Convert CommonJS to AMD.
            var wrapped = commonJs.convert(moduleName, contents);
            var noDefine = wrapped.indexOf("define(") === -1;
            var noConfig = wrapped.indexOf("require.config") === -1;

            if (noDefine && noConfig) {
              wrapped = [
                "define(function(require, exports, module) {",
                  wrapped,
                "});"
              ].join("\n");
            }

            return wrapped;
          }
        });

        // Only log the options during verbose mode.
        grunt.verbose.writeflags(options, "Options");

        // Full optimiziation.
        requirejs.optimize(options, done);
      });
    });
  });
};
<commit_msg>Added jam configuration<commit_after>/*
 * grunt-bbb-requirejs
 * http://gruntjs.com/
 *
 * Copyright (c) 2013 Tim Branyen, Tyler Kellen, contributors
 * Licensed under the MIT license.
 */
"use strict";

module.exports = function(grunt) {
  var ENV = process.env;
  var CWD = process.cwd();

  var fs = require("fs");
  var path = require("path");
  var requirejs = require("requirejs");
  var _ = grunt.util._;
  var log = grunt.log;

  // Convert the contents passed to CommonJS and then return.
  function toCommonJS(moduleName, contents, commonJs) {
    return commonJs.convert(moduleName, String(contents));
  }

  // TODO: extend this to send build log to grunt.log.ok / grunt.log.error by
  // overriding the r.js logger (or submit issue to r.js to expand logging
  // support)
  requirejs.define("node/print", [], function() {
    return function print(msg) {
      if (msg.substring(0, 5) === "Error") {
        grunt.log.errorlns(msg);
        grunt.fail.warn("RequireJS failed.");
      } else {
        grunt.log.oklns(msg);
      }
    };
  });

  grunt.registerTask("list", "Show module dependencies.", function(prop) {
    var options = grunt.config("requirejs") || {};
    var baseUrl = options.baseUrl || "app";
    var done = this.async();
    var exports = {};

    exports.init = function(grunt) {
      var exports = {};
      var _ = grunt.util._;

      exports.list = function(appDir, done) {
        var jsRegExp = /\.js$/;

        requirejs.tools.useLib(function(require) {
          require(["parse", "commonJs"], function(parse, commonJs) {
            var deps = {};
            var files = [];

            // Recursively find all files inside the application directory
            function recurse(dir) {
              fs.readdirSync(dir).forEach(function(name) {
                var subdir = path.resolve(dir, name);
                var stats = fs.statSync(subdir);

                if (stats.isDirectory()) {
                  recurse(subdir);
                } else if (jsRegExp.test(name)) {
                  files.push(subdir);
                }
              });
            }

            // Start with the app directory e.g. app/
            recurse(appDir);

            files.forEach(function(name) {
              var contents = fs.readFileSync(name, "utf8");
              var shortname = name.slice(name.indexOf(appDir));
              var dep, all;

              // Convert to CommonJS first.
              contents = commonJs.convert(name, contents);

              try {
                dep = parse.findDependencies(name, contents)
              } catch (ex) {
                console.log(ex);
              }

              if (dep && dep.length) {
                all = deps[shortname] = parse.findDependencies(name, contents);

                // Remove `require`, `module`, `exports`.
                all.splice(all.indexOf("require"), 1);
                all.splice(all.indexOf("module"), 1);
                all.splice(all.indexOf("exports"), 1);
              }
            });

            console.log(exports.tree(deps));
            done();
          });
        });
      };

      exports.tree = function(obj) {
        var tree = [""];

        function spaces(len, end, start) {
          start = start || " ";
          end = end || " ";

          if (!start) {
            return Array(len+1).join(Array(3).join(end));
          } else {
            return Array(len+1).join(start + Array(2).join(end));
          }
        }

        function traverse(obj, depth) {
          _.each(obj, function(val, key) {
            var len;

            if (_.isArray(val)) {
              tree.push("\u251c" + spaces(depth) + " " + key);

              len = val.length;

              _.each(val, function(val, i) {
                if (_.isString(val)) {
                  if (i == len-1) {
                    tree.push("\u2502 " + spaces(depth+1, "\u2500", "\u2514") + " "
                      + val);
                  } else {
                    tree.push("\u2502 " + spaces(depth+1, "\u2500", "\u251c") + " "
                      + val);
                  }
                } else if (_.isObject(val)) {
                  traverse(obj, depth+1);
                }
              });

              tree.push("\u2502");

            } else if (_.isObject(val)) {
              tree.push(spaces(depth) + key);
              traverse(val, depth+1);
            } else {
              tree.push(spaces(depth) + key);
            }

          });
        }

        traverse(obj, 0);

        tree.pop();

        return tree.join("\n");
      };

      return exports;
    };

    exports.init(grunt).list(path.normalize(baseUrl + "/"), done);
  });

  grunt.registerMultiTask("requirejs", "Build with r.js.", function() {
    // Make the current task reusable within the async callbacks below.
    var task = this;

    // Put this task into `async-mode`, cause we're gonna need it.
    var done = task.async();

    // Cache this function so that we can reuse it within RequireJS's
    // utilities.
    var nodeRequire = require;

    // Access RequireJS's internal utilities.
    requirejs.tools.useLib(function(require) {
      // Get access to the CommonJS convert utility.
      require(["commonJs"], function(commonJs) {
        var options = task.options({
          // Include the main ration file.
          mainConfigFile: "app/config.js",

          // Setting the base url to the distribution directory allows the
          // Uglify minification process to correctly map paths for Source
          // Maps.
          baseUrl: "dist/app",

          // Default location for where scripts are modules.
          moduleDirs: ["dist/app", "dist/test"],

          // Include Almond to slim down the built filesize.
          name: "almond",

          // Set the Bootstrap as the main entry point.
          include: ["main"],
          insertRequire: ["main"],

          // Since we bootstrap with nested `require` calls this option allows
          // R.js to find them.
          findNestedDependencies: true,

          // Wrap everything in an IIFE.
          wrap: true,

          // Jam configuration path.
          jamConfig: "vendor/jam/require.config.js",

          // Output file.
          out: "dist/source.min.js",

          // Enable Source Map generation.
          generateSourceMaps: true,

          // Do not preserve any license comments when working with source maps.
          // These options are incompatible.
          preserveLicenseComments: false,

          // Minify using UglifyJS.
          optimize: "uglify2",

          // Show warnings
          logLevel: 2,

          // Ensure modules are inserted
          skipModuleInsertion: false,

          // If the contents do not contain a define call, then wrap with
          onBuildRead: function (moduleName, filePath, contents) {
            var moduleDir = _.find(options.moduleDirs, function(dir) {
              return filePath.indexOf(path.resolve(CWD, dir)) === 0;
            });

            // Do not execute the conversion on files that do not exist in the
            // main application path.
            if (!moduleDir) {
              return contents;
            }

            // Convert CommonJS to AMD.
            var wrapped = commonJs.convert(moduleName, contents);
            var noDefine = wrapped.indexOf("define(") === -1;
            var noConfig = wrapped.indexOf("require.config") === -1;

            if (noDefine && noConfig) {
              wrapped = [
                "define(function(require, exports, module) {",
                  wrapped,
                "});"
              ].join("\n");
            }

            return wrapped;
          }
        });

        // Merge in the Jam configuration.
        if (grunt.file.exists(options.jamConfig)) {
          _.extend(options, nodeRequire(process.cwd() + "/" + options.jamConfig));
        }

        // Only log the options during verbose mode.
        grunt.verbose.writeflags(options, "Options");

        // Full optimiziation.
        requirejs.optimize(options, done);
      });
    });
  });
};
<|endoftext|>


<commit_before>/*jshint unused:false*/
var iceUnit = (function() {
    'use strict';

    function isFunction(value){
        return typeof value === 'function';
    }

    var injectService = function(serviceName) {
        var service;
        angular.mock.inject(function($injector) {
            service = $injector.get(serviceName);
        });
        return service;
    };

    var getPromiseMock = function(callbackObject) {
        return function() {
            return {
                then: function(successCallback, errorCallback, notifyCallback) {
                    callbackObject.success = successCallback;
                    callbackObject.error = errorCallback;
                    callbackObject.notify = notifyCallback;
                },
                catch: function(errorCallback) {
                    callbackObject.success = null;
                    callbackObject.error = errorCallback;
                }
            };
        };
    };

    var getHttpPromiseMock = function(callbackObject) {
        return function() {
            var promiseMock = getPromiseMock(callbackObject)();

            promiseMock.error = function(errorCallback) {
                callbackObject.error = errorCallback;
            };

            promiseMock.success = function(successCallback) {
                callbackObject.success = successCallback;

                return {
                    error: promiseMock.error
                };
            };

            return promiseMock;
        };
    };

    var extendArray = function(array, otherArray, MakeEachElemOfThisType) {
        otherArray.forEach(function(elem) {
            var instanceElem = new MakeEachElemOfThisType();
            angular.copy(elem, instanceElem);
            array.push(instanceElem);
        });
    };

    var getResourceActionMock = function(isArray, isPayload, callbackObject, actionName, ResourceMock, isInstanceCall) {
        if (typeof isInstanceCall === 'undefined') {
            isInstanceCall = false;
        }

        callbackObject[actionName] = {};

        //for GET actions (and non-GET instance actions):
        //    return function ([paramObject], [successCallback], [errorCallback]) {}
        //for non-GET 'class' actions:
        //    return function ([paramObject], postData, [successCallback], [errorCallback]) {}

        return function (a1, a2, a3, a4) {
            var successCallback, errorCallback;

            /* jshint -W086 */ /* (purposefully fall through case statements) */
            switch(arguments.length) {
                case 4:
                    successCallback = a3;
                    errorCallback = a4;
                    break;
                case 3:
                    //fallthrough
                case 2:
                    if (isFunction(a2)) {
                        if (isFunction(a1)) {
                            successCallback = a1;
                            errorCallback = a2;
                            break;
                        }

                        successCallback = a2;
                        errorCallback = a3;
                        //fallthrough
                    } else {
                        //paramObject = a1;
                        //postData = a2;
                        successCallback = a3;
                        break;
                    }
                case 1:
                    if (isFunction(a1)) {
                        successCallback = a1;
                    }
                    //else if (isPayload) {
                    //    postData = a1;
                    //}
                    //else {
                    //    paramObject = a1;
                    //}
                    break;
                case 0:
                    break;
            }
            /* jshint +W086 */ /* (purposefully fall through case statements) */

            var resultReferenceObject;
            if (isArray) {
                resultReferenceObject = [];
                resultReferenceObject.$resolved = false;
            } else {
                // {}
                resultReferenceObject = new ResourceMock();
                resultReferenceObject.$resolved = false;
            }

            if (!isInstanceCall) {
                if (typeof ResourceMock.prototype.$save !== 'function') {
                    // add these if not already added by ResourceMockBuilder.build (see ResourceActionMockBuilder)
                    ResourceMock.prototype.$save = getResourceActionMock(false, false, callbackObject, '$save', ResourceMock, true);
                    ResourceMock.prototype.$remove = getResourceActionMock(false, false, callbackObject, '$remove', ResourceMock, true);
                    ResourceMock.prototype.$delete = getResourceActionMock(false, false, callbackObject, '$delete', ResourceMock, true);
                }
            }

            callbackObject[actionName].success = function(value, responseHeaders) {
                if (isArray) {
                    extendArray(resultReferenceObject, value, ResourceMock);
                } else {
                    angular.copy(value, resultReferenceObject);
                }

                resultReferenceObject.$resolved = true;

                if (typeof successCallback !== 'undefined') {
                    successCallback(value, responseHeaders);
                }
            };

            callbackObject[actionName].error = function(httpResponse) {
                resultReferenceObject.$resolved = true;

                if (typeof errorCallback !== 'undefined') {
                    errorCallback(httpResponse);
                }
            };

            resultReferenceObject.$promise = getPromiseMock(callbackObject[actionName])();

            if (isInstanceCall) {
                return resultReferenceObject.$promise;
            }
            return resultReferenceObject;
        };
    };

    var mock = {
        promise: getPromiseMock,
        $httpPromise: getHttpPromiseMock
    };

    function ControllerScopeBuilder(moduleName, controllerName) {
        this.moduleName = moduleName;
        this.controllerName = controllerName;
        this.parentScope = null;
        this.injectionLocals = {};
        this.loadModule = true;
    }

    ControllerScopeBuilder.prototype.withMock = function(injectKey, mock) {
        this.injectionLocals[injectKey] = mock;
        return this;
    };

    ControllerScopeBuilder.prototype.withParentScope = function(parentScopeObject) {
        this.parentScope = parentScopeObject;
        return this;
    };

    ControllerScopeBuilder.prototype.skipModuleLoad = function() {
        this.loadModule = false;
        return this;
    };

    ControllerScopeBuilder.prototype.build = function() {
        if (this.loadModule === true) {
            angular.mock.module(this.moduleName);
        }

        var $controller = injectService('$controller');
        var $rootScope = injectService('$rootScope');

        var $scope;

        if (this.parentScope === null) {
            $scope = $rootScope.$new();
        } else {
            $scope = this.parentScope;
        }

        this.injectionLocals.$scope = $scope;

        $controller(this.controllerName, this.injectionLocals);

        return $scope;
    };

    function ServiceBuilder(moduleName, serviceName) {
        this.moduleName = moduleName;
        this.serviceName = serviceName;
        this.provideValues = [];
    }

    ServiceBuilder.prototype.withMock = function(injectKey, mock) {
        this.provideValues.push({injectKey: injectKey, mock: mock});
        return this;
    };

    ServiceBuilder.prototype.build = function() {
        var _this = this;
        angular.mock.module(this.moduleName, function($provide) {
            if (_this.provideValues.length > 0) {
                _this.provideValues.forEach(function(provideVal) {
                    $provide.value(provideVal.injectKey, provideVal.mock);
                });
            }
        });

        return injectService(this.serviceName);
    };

    function DirectiveBuilder(moduleName, elementHtml) {
        this.moduleName = moduleName;
        this.elementHtml = elementHtml;
        this.scopeFields = [];
        this.loadModule = true;
    }

    DirectiveBuilder.prototype.withScopeField = function(fieldName, fieldValue) {
        this.scopeFields.push({name: fieldName, value: fieldValue});
        return this;
    };

    DirectiveBuilder.prototype.skipModuleLoad = function() {
        this.loadModule = false;
        return this;
    };

    DirectiveBuilder.prototype.build = function() {
        if (this.loadModule === true) {
            angular.mock.module(this.moduleName);
        }

        var $compile = injectService('$compile');
        var $rootScope = injectService('$rootScope');

        var $scope = $rootScope.$new();
        if (this.scopeFields.length > 0) {
            this.scopeFields.forEach(function(scopeField) {
                $scope[scopeField.name] = scopeField.value;
            });
        }

        var element = $compile(this.elementHtml)($scope);
        $scope.$digest();

        return {
            $scope: $scope,
            element: element
        };
    };

    function ResourceMockBuilder(callbackObject) {
        this.actions = [
            {name: 'get', isArray: false, isPayload: false, hasInstanceAction: false},
            {name: 'save', isArray: false, isPayload: true, hasInstanceAction: true},
            {name: 'query', isArray: true, isPayload: false, hasInstanceAction: false},
            {name: 'remove', isArray: false, isPayload: true, hasInstanceAction: true},
            {name: 'delete', isArray: false, isPayload: true, hasInstanceAction: true}
        ];
        this.callbackObject = callbackObject;
        this.ResourceMock = function() {};
    }

    ResourceMockBuilder.prototype.withCustomAction = function(actionName, isArray, isPayload, hasInstanceAction) {
        this.actions.push({name: actionName, isArray: isArray, isPayload: isPayload, hasInstanceAction: hasInstanceAction});
        return this;
    };

    ResourceMockBuilder.prototype.build = function() {
        if (this.actions.length > 0) {

            var _this = this;
            this.actions.forEach(function(action) {
                _this.ResourceMock[action.name] = getResourceActionMock(action.isArray, action.isPayload, _this.callbackObject, action.name, _this.ResourceMock, false);

                if (action.hasInstanceAction) {
                    _this.ResourceMock.prototype['$' + action.name] = getResourceActionMock(action.isArray, action.isPayload, _this.callbackObject, '$' + action.name, _this.ResourceMock, true);
                }
            });
        }

        return this.ResourceMock;
    };

    function ResourceActionMockBuilder(actionName, callbackObject) {
        this.actionName = actionName;
        this.callbackObject = callbackObject;
        this.isArray = false;
        this.isPayload = false;
        this.ResourceMock = function() {};
    }

    ResourceActionMockBuilder.prototype.acceptsPayload = function(isPayload) {
        if (typeof isPayload === 'undefined') {
            isPayload = true;
        }
        this.isPayload = isPayload;
        return this;
    };

    ResourceActionMockBuilder.prototype.returnsArray = function(isArray) {
        if (typeof isArray === 'undefined') {
            isArray = true;
        }
        this.isArray = isArray;
        return this;
    };

    ResourceActionMockBuilder.prototype.build = function() {
        return getResourceActionMock(this.isArray, this.isPayload, this.callbackObject, this.actionName, this.ResourceMock);
    };

    var builder = {
        controllerScope: function(moduleName, controllerName) {
            if (typeof moduleName === 'undefined') {
                return undefined;
            }
            if (typeof controllerName === 'undefined') {
                return undefined;
            }
            return new ControllerScopeBuilder(moduleName, controllerName);
        },
        service: function(moduleName, serviceName) {
            if (typeof moduleName === 'undefined') {
                return undefined;
            }
            if (typeof serviceName === 'undefined') {
                return undefined;
            }
            return new ServiceBuilder(moduleName, serviceName);
        },
        directive: function(moduleName, elementHtml) {
            if (typeof moduleName === 'undefined') {
                return undefined;
            }
            if (typeof elementHtml === 'undefined') {
                return undefined;
            }
            return new DirectiveBuilder(moduleName, elementHtml);
        },
        $resourceMock: function(callbackObject) {
            if (typeof callbackObject === 'undefined') {
                return undefined;
            }
            return new ResourceMockBuilder(callbackObject);
        },
        $resourceActionMock: function(actionName, callbackObject) {
            if (typeof actionName === 'undefined') {
                return undefined;
            }
            if (typeof callbackObject === 'undefined') {
                return undefined;
            }
            return new ResourceActionMockBuilder(actionName, callbackObject);
        }
    };

    return {
        inject: injectService,
        mock: mock,
        builder: builder
    };
})();
<commit_msg>[bverbist] iceUnit : fix use of parent scope in controllerScope builder<commit_after>/*jshint unused:false*/
var iceUnit = (function() {
    'use strict';

    function isFunction(value){
        return typeof value === 'function';
    }

    var injectService = function(serviceName) {
        var service;
        angular.mock.inject(function($injector) {
            service = $injector.get(serviceName);
        });
        return service;
    };

    var getPromiseMock = function(callbackObject) {
        return function() {
            return {
                then: function(successCallback, errorCallback, notifyCallback) {
                    callbackObject.success = successCallback;
                    callbackObject.error = errorCallback;
                    callbackObject.notify = notifyCallback;
                },
                catch: function(errorCallback) {
                    callbackObject.success = null;
                    callbackObject.error = errorCallback;
                }
            };
        };
    };

    var getHttpPromiseMock = function(callbackObject) {
        return function() {
            var promiseMock = getPromiseMock(callbackObject)();

            promiseMock.error = function(errorCallback) {
                callbackObject.error = errorCallback;
            };

            promiseMock.success = function(successCallback) {
                callbackObject.success = successCallback;

                return {
                    error: promiseMock.error
                };
            };

            return promiseMock;
        };
    };

    var extendArray = function(array, otherArray, MakeEachElemOfThisType) {
        otherArray.forEach(function(elem) {
            var instanceElem = new MakeEachElemOfThisType();
            angular.copy(elem, instanceElem);
            array.push(instanceElem);
        });
    };

    var getResourceActionMock = function(isArray, isPayload, callbackObject, actionName, ResourceMock, isInstanceCall) {
        if (typeof isInstanceCall === 'undefined') {
            isInstanceCall = false;
        }

        callbackObject[actionName] = {};

        //for GET actions (and non-GET instance actions):
        //    return function ([paramObject], [successCallback], [errorCallback]) {}
        //for non-GET 'class' actions:
        //    return function ([paramObject], postData, [successCallback], [errorCallback]) {}

        return function (a1, a2, a3, a4) {
            var successCallback, errorCallback;

            /* jshint -W086 */ /* (purposefully fall through case statements) */
            switch(arguments.length) {
                case 4:
                    successCallback = a3;
                    errorCallback = a4;
                    break;
                case 3:
                    //fallthrough
                case 2:
                    if (isFunction(a2)) {
                        if (isFunction(a1)) {
                            successCallback = a1;
                            errorCallback = a2;
                            break;
                        }

                        successCallback = a2;
                        errorCallback = a3;
                        //fallthrough
                    } else {
                        //paramObject = a1;
                        //postData = a2;
                        successCallback = a3;
                        break;
                    }
                case 1:
                    if (isFunction(a1)) {
                        successCallback = a1;
                    }
                    //else if (isPayload) {
                    //    postData = a1;
                    //}
                    //else {
                    //    paramObject = a1;
                    //}
                    break;
                case 0:
                    break;
            }
            /* jshint +W086 */ /* (purposefully fall through case statements) */

            var resultReferenceObject;
            if (isArray) {
                resultReferenceObject = [];
                resultReferenceObject.$resolved = false;
            } else {
                // {}
                resultReferenceObject = new ResourceMock();
                resultReferenceObject.$resolved = false;
            }

            if (!isInstanceCall) {
                if (typeof ResourceMock.prototype.$save !== 'function') {
                    // add these if not already added by ResourceMockBuilder.build (see ResourceActionMockBuilder)
                    ResourceMock.prototype.$save = getResourceActionMock(false, false, callbackObject, '$save', ResourceMock, true);
                    ResourceMock.prototype.$remove = getResourceActionMock(false, false, callbackObject, '$remove', ResourceMock, true);
                    ResourceMock.prototype.$delete = getResourceActionMock(false, false, callbackObject, '$delete', ResourceMock, true);
                }
            }

            callbackObject[actionName].success = function(value, responseHeaders) {
                if (isArray) {
                    extendArray(resultReferenceObject, value, ResourceMock);
                } else {
                    angular.copy(value, resultReferenceObject);
                }

                resultReferenceObject.$resolved = true;

                if (typeof successCallback !== 'undefined') {
                    successCallback(value, responseHeaders);
                }
            };

            callbackObject[actionName].error = function(httpResponse) {
                resultReferenceObject.$resolved = true;

                if (typeof errorCallback !== 'undefined') {
                    errorCallback(httpResponse);
                }
            };

            resultReferenceObject.$promise = getPromiseMock(callbackObject[actionName])();

            if (isInstanceCall) {
                return resultReferenceObject.$promise;
            }
            return resultReferenceObject;
        };
    };

    var mock = {
        promise: getPromiseMock,
        $httpPromise: getHttpPromiseMock
    };

    function ControllerScopeBuilder(moduleName, controllerName) {
        this.moduleName = moduleName;
        this.controllerName = controllerName;
        this.parentScope = null;
        this.injectionLocals = {};
        this.loadModule = true;
    }

    ControllerScopeBuilder.prototype.withMock = function(injectKey, mock) {
        this.injectionLocals[injectKey] = mock;
        return this;
    };

    ControllerScopeBuilder.prototype.withParentScope = function(parentScopeObject) {
        this.parentScope = parentScopeObject;
        return this;
    };

    ControllerScopeBuilder.prototype.skipModuleLoad = function() {
        this.loadModule = false;
        return this;
    };

    ControllerScopeBuilder.prototype.build = function() {
        if (this.loadModule === true) {
            angular.mock.module(this.moduleName);
        }

        var $controller = injectService('$controller');
        var $rootScope = injectService('$rootScope');

        var $scope;

        if (this.parentScope === null) {
            $scope = $rootScope.$new();
        } else {
            var $parent = $rootScope.$new();
            angular.extend($parent, this.parentScope);
            $scope = $parent.$new();
        }

        this.injectionLocals.$scope = $scope;

        $controller(this.controllerName, this.injectionLocals);

        return $scope;
    };

    function ServiceBuilder(moduleName, serviceName) {
        this.moduleName = moduleName;
        this.serviceName = serviceName;
        this.provideValues = [];
    }

    ServiceBuilder.prototype.withMock = function(injectKey, mock) {
        this.provideValues.push({injectKey: injectKey, mock: mock});
        return this;
    };

    ServiceBuilder.prototype.build = function() {
        var _this = this;
        angular.mock.module(this.moduleName, function($provide) {
            if (_this.provideValues.length > 0) {
                _this.provideValues.forEach(function(provideVal) {
                    $provide.value(provideVal.injectKey, provideVal.mock);
                });
            }
        });

        return injectService(this.serviceName);
    };

    function DirectiveBuilder(moduleName, elementHtml) {
        this.moduleName = moduleName;
        this.elementHtml = elementHtml;
        this.scopeFields = [];
        this.loadModule = true;
    }

    DirectiveBuilder.prototype.withScopeField = function(fieldName, fieldValue) {
        this.scopeFields.push({name: fieldName, value: fieldValue});
        return this;
    };

    DirectiveBuilder.prototype.skipModuleLoad = function() {
        this.loadModule = false;
        return this;
    };

    DirectiveBuilder.prototype.build = function() {
        if (this.loadModule === true) {
            angular.mock.module(this.moduleName);
        }

        var $compile = injectService('$compile');
        var $rootScope = injectService('$rootScope');

        var $scope = $rootScope.$new();
        if (this.scopeFields.length > 0) {
            this.scopeFields.forEach(function(scopeField) {
                $scope[scopeField.name] = scopeField.value;
            });
        }

        var element = $compile(this.elementHtml)($scope);
        $scope.$digest();

        return {
            $scope: $scope,
            element: element
        };
    };

    function ResourceMockBuilder(callbackObject) {
        this.actions = [
            {name: 'get', isArray: false, isPayload: false, hasInstanceAction: false},
            {name: 'save', isArray: false, isPayload: true, hasInstanceAction: true},
            {name: 'query', isArray: true, isPayload: false, hasInstanceAction: false},
            {name: 'remove', isArray: false, isPayload: true, hasInstanceAction: true},
            {name: 'delete', isArray: false, isPayload: true, hasInstanceAction: true}
        ];
        this.callbackObject = callbackObject;
        this.ResourceMock = function() {};
    }

    ResourceMockBuilder.prototype.withCustomAction = function(actionName, isArray, isPayload, hasInstanceAction) {
        this.actions.push({name: actionName, isArray: isArray, isPayload: isPayload, hasInstanceAction: hasInstanceAction});
        return this;
    };

    ResourceMockBuilder.prototype.build = function() {
        if (this.actions.length > 0) {

            var _this = this;
            this.actions.forEach(function(action) {
                _this.ResourceMock[action.name] = getResourceActionMock(action.isArray, action.isPayload, _this.callbackObject, action.name, _this.ResourceMock, false);

                if (action.hasInstanceAction) {
                    _this.ResourceMock.prototype['$' + action.name] = getResourceActionMock(action.isArray, action.isPayload, _this.callbackObject, '$' + action.name, _this.ResourceMock, true);
                }
            });
        }

        return this.ResourceMock;
    };

    function ResourceActionMockBuilder(actionName, callbackObject) {
        this.actionName = actionName;
        this.callbackObject = callbackObject;
        this.isArray = false;
        this.isPayload = false;
        this.ResourceMock = function() {};
    }

    ResourceActionMockBuilder.prototype.acceptsPayload = function(isPayload) {
        if (typeof isPayload === 'undefined') {
            isPayload = true;
        }
        this.isPayload = isPayload;
        return this;
    };

    ResourceActionMockBuilder.prototype.returnsArray = function(isArray) {
        if (typeof isArray === 'undefined') {
            isArray = true;
        }
        this.isArray = isArray;
        return this;
    };

    ResourceActionMockBuilder.prototype.build = function() {
        return getResourceActionMock(this.isArray, this.isPayload, this.callbackObject, this.actionName, this.ResourceMock);
    };

    var builder = {
        controllerScope: function(moduleName, controllerName) {
            if (typeof moduleName === 'undefined') {
                return undefined;
            }
            if (typeof controllerName === 'undefined') {
                return undefined;
            }
            return new ControllerScopeBuilder(moduleName, controllerName);
        },
        service: function(moduleName, serviceName) {
            if (typeof moduleName === 'undefined') {
                return undefined;
            }
            if (typeof serviceName === 'undefined') {
                return undefined;
            }
            return new ServiceBuilder(moduleName, serviceName);
        },
        directive: function(moduleName, elementHtml) {
            if (typeof moduleName === 'undefined') {
                return undefined;
            }
            if (typeof elementHtml === 'undefined') {
                return undefined;
            }
            return new DirectiveBuilder(moduleName, elementHtml);
        },
        $resourceMock: function(callbackObject) {
            if (typeof callbackObject === 'undefined') {
                return undefined;
            }
            return new ResourceMockBuilder(callbackObject);
        },
        $resourceActionMock: function(actionName, callbackObject) {
            if (typeof actionName === 'undefined') {
                return undefined;
            }
            if (typeof callbackObject === 'undefined') {
                return undefined;
            }
            return new ResourceActionMockBuilder(actionName, callbackObject);
        }
    };

    return {
        inject: injectService,
        mock: mock,
        builder: builder
    };
})();
<|endoftext|>


<commit_before>var compiler = require('./lib/compiler');

module.exports = function(content) {
	this.cacheable();

	var opts = {
		sourceMap: this.sourceMap,
		sourcePath: this.resourcePath,
		target: this.target,
		ENV_DEBUG: this.debug,
		standalone: false,
		bare: true
	};

	try {
		var result = compiler.compile(content, opts);
		var js = result.toString();
		this.callback(null, js, result.sourcemap);
	} catch(e) {
		this.emitError(e.prettyMessage());
		// this.callback(null,"");
	}

}<commit_msg>Allow passing in environment-variables from webpack<commit_after>var compiler = require('./lib/compiler');

module.exports = function(content) {
	this.cacheable();

	var opts = {
		sourceMap: this.sourceMap,
		sourcePath: this.resourcePath,
		target: this.target,
		ENV_DEBUG: this.debug,
		standalone: false,
		bare: true
	};
	if(this.env){
		opts.env = this.env;
	}

	try {
		var result = compiler.compile(content, opts);
		var js = result.toString();
		this.callback(null, js, result.sourcemap);
	} catch(e) {
		this.emitError(e.prettyMessage());
		// this.callback(null,"");
	}

}<|endoftext|>


<commit_before>var _ = require('lodash'),
    utils =  require('../../utils'),
    driver = utils.getDriver(),
    C = driver.constants,
    matrix,
    objects,
    affectedCnt,
    roomObjects,
    roomTerrain;

function canMove(object) {
    return object.type == 'powerCreep' ||
        (!!object._pulled || !object._oldFatigue && _.some(object.body, i => i.hits > 0 && i.type == C.MOVE));
}

function checkObstacleAtXY(x,y,object, roomIsInSafeMode) {
    var hasObstacle = false, hasRoad = false;
    _.forEach(roomObjects, (i) => {
        if (i.x != x || i.y != y) {
            return;
        }
        if (i.type == 'creep' && !objects[i._id] && (!roomIsInSafeMode || roomIsInSafeMode != object.user || roomIsInSafeMode == object.user && object.user == i.user) ||
            i.type != 'creep' && _.contains(C.OBSTACLE_OBJECT_TYPES, i.type) ||
            i.type == 'rampart' && !i.isPublic && i.user != object.user ||
            i.type == 'constructionSite' && i.user == object.user && _.contains(C.OBSTACLE_OBJECT_TYPES,
                i.structureType)) {
            hasObstacle = true;
            return false;
        }
        if(i.type == 'road') {
            hasRoad = true;
        }
    });
    if(hasObstacle) {
        return true;
    }
    return utils.checkTerrain(roomTerrain, x, y, C.TERRAIN_MASK_WALL) && !hasRoad;

}

function calcResourcesWeight(creep) {
    var totalCarry = 0, weight = 0;
    C.RESOURCES_ALL.forEach(resourceType => {
        totalCarry += creep[resourceType] || 0;
    });
    for(var i = creep.body.length-1; i >= 0; i--) {
        if(!totalCarry) {
            break;
        }
        var part = creep.body[i];
        if(part.type != C.CARRY || !part.hits) {
            continue;
        }
        var boost = 1;
        if(part.boost) {
            boost = C.BOOSTS[C.CARRY][part.boost].capacity || 1;
        }
        totalCarry -= Math.min(totalCarry, C.CARRY_CAPACITY * boost);
        weight++;
    }
    return weight;
}

exports.init = function(_roomObjects, _roomTerrain) {
    matrix = {};
    objects = {};
    affectedCnt = {};
    roomObjects = _roomObjects;
    roomTerrain = _roomTerrain;
};

exports.addPulling = function(object, target) {
    const checkRecursiveTarget = t=>t._id==object._id || !!t._pull && !!roomObjects[t._pull] && checkRecursiveTarget(roomObjects[t._pull]);
    if(!checkRecursiveTarget(target)) {
        object._pull = target._id;
        target._pulled = object._id;
    }
};

exports.removePulling = function(object) {
    if(object._pull && !!roomObjects[object._pull]) {
        delete roomObjects[object._pull]._pulled;
    }
    delete object._pull;
};

exports.add = function(object, dx, dy) {
    var newX = object.x + dx,
        newY = object.y + dy;

    if (newX >= 50) newX = 49;
    if (newY >= 50) newY = 49;
    if (newX < 0) newX = 0;
    if (newY < 0) newY = 0;

    var key = `${newX},${newY}`;
    matrix[key] = matrix[key] || [];
    matrix[key].push(object);

    affectedCnt[key] = affectedCnt[key]+1 || 1;
};

exports.isTileBusy = function(x,y) {
    return !!matrix[`${x},${y}`];
};

exports.check = function(roomIsInSafeMode) {
    var newMatrix = {};

    for(var i in matrix) {

        var [x,y] = i.split(/,/),
            resultingMoveObject;

        x = parseInt(x);
        y = parseInt(y);

        if(matrix[i].length > 1) {
            var rates = _.map(matrix[i], (object) => {
                var moves = object.type == 'powerCreep' ? 0 :
                        utils.calcBodyEffectiveness(object.body, C.MOVE, 'fatigue', 1),
                    weight = object.type == 'powerCreep' ? 0 :
                        _.filter(object.body, (i) => i.type != C.MOVE && i.type != C.CARRY).length;
                weight += object.type == 'powerCreep' ? 0 :
                    calcResourcesWeight(object);
                weight = weight || 1;
                var key = `${object.x},${object.y}`,
                    rate1 = affectedCnt[key] || 0;
                if(matrix[key] && _.any(matrix[key], {x,y})) {
                    rate1 = 100;
                }

                return {
                    object,
                    rate1,
                    rate2: !!object._pulled?1:0,
                    rate3: !!object._pull?1:0,
                    rate4: moves / weight
                };
            });

            rates.sort((a,b) => b.rate1 - a.rate1 || b.rate2 - a.rate2 || b.rate3 - a.rate3 || b.rate4 - a.rate4);

            resultingMoveObject = rates[0].object;
        }
        else {
            resultingMoveObject = matrix[i][0];
        }

        objects[resultingMoveObject._id] = {x,y};

        newMatrix[i] = resultingMoveObject;
    }

    matrix = newMatrix;

    function removeFromMatrix(i) {
        var object = matrix[i];
        objects[matrix[i]._id] = null;
        delete matrix[i];

        if(object) {
            var key = `${object.x},${object.y}`;
            if(matrix[key]) {
                removeFromMatrix(key);
            }
        }
    }

    for(var i in matrix) {

        var [x,y] = i.split(/,/);

        x = parseInt(x);
        y = parseInt(y);

        var object = matrix[i];

        if(!!object._pulled && !!roomObjects[object._pulled]) {
            if(roomObjects[object._pulled]._pull != object._id || i != `${roomObjects[object._pulled].x},${roomObjects[object._pulled].y}`) {
                delete roomObjects[object._pulled]._pull;
                delete object._pulled;
            }
        }

        if(!canMove(object) || !!checkObstacleAtXY(x,y, object, roomIsInSafeMode)) {
            removeFromMatrix(i);
        }
    }
};

exports.execute = function(object, scope) {

    const {bulk, roomController, gameTime} = scope;

    var move = objects[object._id];
    if(!move) {
        return;
    }

    if(!canMove(object)) {
        return;
    }

    var cellObjects = _.filter(roomObjects, (i) => i.x == move.x && i.y == move.y);

    var fatigueRate = 2;

    if(_.any(cellObjects, {type: 'swamp'}) ||
        utils.checkTerrain(roomTerrain, move.x, move.y, C.TERRAIN_MASK_SWAMP)) {
        fatigueRate = 10;
    }

    var road = _.find(cellObjects, {type: 'road'});

    if(road) {
        fatigueRate = 1;
        road.nextDecayTime -= C.ROAD_WEAROUT * object.body.length;
        bulk.update(road, {nextDecayTime: road.nextDecayTime});
    }

    if(!roomController || roomController.user === object.user || !(roomController.safeMode > gameTime)) {
        var constructionSite = _.find(cellObjects, (i) => i.type == 'constructionSite' && i.user != object.user);
        if (constructionSite) {
            bulk.remove(constructionSite._id);
            if(constructionSite.progress > 1) {
                require('./creeps/_create-energy')(constructionSite.x, constructionSite.y,
                    constructionSite.room, Math.floor(constructionSite.progress/2), 'energy', scope);
            }
        }
    }

    var fatigue;
    if(object.type == 'creep') {
        fatigue = _(object.body).filter((i) => i.type != C.MOVE && i.type != C.CARRY).size();
        fatigue += calcResourcesWeight(object);
        fatigue *= fatigueRate;
    }

    if(utils.isAtEdge(move) && !utils.isAtEdge(object)) {
        fatigue = 0;
        object._fatigue = 0;
        bulk.update(object, { x: move.x, y: move.y, fatigue });
    } else {
        bulk.update(object, { x: move.x, y: move.y });
        if(object.type == 'creep') {
            require('./creeps/_add-fatigue')(object, fatigue, scope);
        }
    }
};
<commit_msg>fix(processor): bug in power creeps movement on roads<commit_after>var _ = require('lodash'),
    utils =  require('../../utils'),
    driver = utils.getDriver(),
    C = driver.constants,
    matrix,
    objects,
    affectedCnt,
    roomObjects,
    roomTerrain;

function canMove(object) {
    return object.type == 'powerCreep' ||
        (!!object._pulled || !object._oldFatigue && _.some(object.body, i => i.hits > 0 && i.type == C.MOVE));
}

function checkObstacleAtXY(x,y,object, roomIsInSafeMode) {
    var hasObstacle = false, hasRoad = false;
    _.forEach(roomObjects, (i) => {
        if (i.x != x || i.y != y) {
            return;
        }
        if (i.type == 'creep' && !objects[i._id] && (!roomIsInSafeMode || roomIsInSafeMode != object.user || roomIsInSafeMode == object.user && object.user == i.user) ||
            i.type != 'creep' && _.contains(C.OBSTACLE_OBJECT_TYPES, i.type) ||
            i.type == 'rampart' && !i.isPublic && i.user != object.user ||
            i.type == 'constructionSite' && i.user == object.user && _.contains(C.OBSTACLE_OBJECT_TYPES,
                i.structureType)) {
            hasObstacle = true;
            return false;
        }
        if(i.type == 'road') {
            hasRoad = true;
        }
    });
    if(hasObstacle) {
        return true;
    }
    return utils.checkTerrain(roomTerrain, x, y, C.TERRAIN_MASK_WALL) && !hasRoad;

}

function calcResourcesWeight(creep) {
    var totalCarry = 0, weight = 0;
    C.RESOURCES_ALL.forEach(resourceType => {
        totalCarry += creep[resourceType] || 0;
    });
    for(var i = creep.body.length-1; i >= 0; i--) {
        if(!totalCarry) {
            break;
        }
        var part = creep.body[i];
        if(part.type != C.CARRY || !part.hits) {
            continue;
        }
        var boost = 1;
        if(part.boost) {
            boost = C.BOOSTS[C.CARRY][part.boost].capacity || 1;
        }
        totalCarry -= Math.min(totalCarry, C.CARRY_CAPACITY * boost);
        weight++;
    }
    return weight;
}

exports.init = function(_roomObjects, _roomTerrain) {
    matrix = {};
    objects = {};
    affectedCnt = {};
    roomObjects = _roomObjects;
    roomTerrain = _roomTerrain;
};

exports.addPulling = function(object, target) {
    const checkRecursiveTarget = t=>t._id==object._id || !!t._pull && !!roomObjects[t._pull] && checkRecursiveTarget(roomObjects[t._pull]);
    if(!checkRecursiveTarget(target)) {
        object._pull = target._id;
        target._pulled = object._id;
    }
};

exports.removePulling = function(object) {
    if(object._pull && !!roomObjects[object._pull]) {
        delete roomObjects[object._pull]._pulled;
    }
    delete object._pull;
};

exports.add = function(object, dx, dy) {
    var newX = object.x + dx,
        newY = object.y + dy;

    if (newX >= 50) newX = 49;
    if (newY >= 50) newY = 49;
    if (newX < 0) newX = 0;
    if (newY < 0) newY = 0;

    var key = `${newX},${newY}`;
    matrix[key] = matrix[key] || [];
    matrix[key].push(object);

    affectedCnt[key] = affectedCnt[key]+1 || 1;
};

exports.isTileBusy = function(x,y) {
    return !!matrix[`${x},${y}`];
};

exports.check = function(roomIsInSafeMode) {
    var newMatrix = {};

    for(var i in matrix) {

        var [x,y] = i.split(/,/),
            resultingMoveObject;

        x = parseInt(x);
        y = parseInt(y);

        if(matrix[i].length > 1) {
            var rates = _.map(matrix[i], (object) => {
                var moves = object.type == 'powerCreep' ? 0 :
                        utils.calcBodyEffectiveness(object.body, C.MOVE, 'fatigue', 1),
                    weight = object.type == 'powerCreep' ? 0 :
                        _.filter(object.body, (i) => i.type != C.MOVE && i.type != C.CARRY).length;
                weight += object.type == 'powerCreep' ? 0 :
                    calcResourcesWeight(object);
                weight = weight || 1;
                var key = `${object.x},${object.y}`,
                    rate1 = affectedCnt[key] || 0;
                if(matrix[key] && _.any(matrix[key], {x,y})) {
                    rate1 = 100;
                }

                return {
                    object,
                    rate1,
                    rate2: !!object._pulled?1:0,
                    rate3: !!object._pull?1:0,
                    rate4: moves / weight
                };
            });

            rates.sort((a,b) => b.rate1 - a.rate1 || b.rate2 - a.rate2 || b.rate3 - a.rate3 || b.rate4 - a.rate4);

            resultingMoveObject = rates[0].object;
        }
        else {
            resultingMoveObject = matrix[i][0];
        }

        objects[resultingMoveObject._id] = {x,y};

        newMatrix[i] = resultingMoveObject;
    }

    matrix = newMatrix;

    function removeFromMatrix(i) {
        var object = matrix[i];
        objects[matrix[i]._id] = null;
        delete matrix[i];

        if(object) {
            var key = `${object.x},${object.y}`;
            if(matrix[key]) {
                removeFromMatrix(key);
            }
        }
    }

    for(var i in matrix) {

        var [x,y] = i.split(/,/);

        x = parseInt(x);
        y = parseInt(y);

        var object = matrix[i];

        if(!!object._pulled && !!roomObjects[object._pulled]) {
            if(roomObjects[object._pulled]._pull != object._id || i != `${roomObjects[object._pulled].x},${roomObjects[object._pulled].y}`) {
                delete roomObjects[object._pulled]._pull;
                delete object._pulled;
            }
        }

        if(!canMove(object) || !!checkObstacleAtXY(x,y, object, roomIsInSafeMode)) {
            removeFromMatrix(i);
        }
    }
};

exports.execute = function(object, scope) {

    const {bulk, roomController, gameTime} = scope;

    var move = objects[object._id];
    if(!move) {
        return;
    }

    if(!canMove(object)) {
        return;
    }

    var cellObjects = _.filter(roomObjects, (i) => i.x == move.x && i.y == move.y);

    var fatigueRate = 2;

    if(_.any(cellObjects, {type: 'swamp'}) ||
        utils.checkTerrain(roomTerrain, move.x, move.y, C.TERRAIN_MASK_SWAMP)) {
        fatigueRate = 10;
    }

    var road = _.find(cellObjects, {type: 'road'});

    if(road) {
        fatigueRate = 1;
        if(object.type == 'powerCreep') {
            road.nextDecayTime -= C.ROAD_WEAROUT_POWER_CREEP;
        }
        else {
            road.nextDecayTime -= C.ROAD_WEAROUT * object.body.length;
        }
        bulk.update(road, {nextDecayTime: road.nextDecayTime});
    }

    if(!roomController || roomController.user === object.user || !(roomController.safeMode > gameTime)) {
        var constructionSite = _.find(cellObjects, (i) => i.type == 'constructionSite' && i.user != object.user);
        if (constructionSite) {
            bulk.remove(constructionSite._id);
            if(constructionSite.progress > 1) {
                require('./creeps/_create-energy')(constructionSite.x, constructionSite.y,
                    constructionSite.room, Math.floor(constructionSite.progress/2), 'energy', scope);
            }
        }
    }

    var fatigue;
    if(object.type == 'creep') {
        fatigue = _(object.body).filter((i) => i.type != C.MOVE && i.type != C.CARRY).size();
        fatigue += calcResourcesWeight(object);
        fatigue *= fatigueRate;
    }

    if(utils.isAtEdge(move) && !utils.isAtEdge(object)) {
        fatigue = 0;
        object._fatigue = 0;
        bulk.update(object, { x: move.x, y: move.y, fatigue });
    } else {
        bulk.update(object, { x: move.x, y: move.y });
        if(object.type == 'creep') {
            require('./creeps/_add-fatigue')(object, fatigue, scope);
        }
    }
};
<|endoftext|>


<commit_before>var app = angular.module('myApp', []);

app.controller('myFactoryCtrl', function($scope, myFactory) {
    $scope.data = {};

    $scope.updateMovie = function() {
        myFactory.setMovie($scope.data.movie);
    };

    $scope.submitMovie = function() {
        myFactory.callIomdb()
            .then(function(data) {
              $scope.data.movieData = data;
            }, function(data) {
                alert(data);
            })
    };
});

app.factory('myFactory', function($http, $q) {
    var service = {};
    var baseUrl = 'http://www.omdbapi.com/?t=';
    var _movie = '';
    var _finalUrl = '';

    var makeUrl = function() {
        _movie = _movie.split(' ').join('+');
        _finalUrl = baseUrl + _movie + '&plot=short&r=json'
        return _finalUrl;
    }

    service.setMovie = function(movie) {
        _movie = movie;
    }

    service.getMovie = function() {
        return _movie;
    }

    service.callIomdb = function() {
        makeUrl();
        var deferred = $q.defer();
        $http({
            method: 'GET',
            url: _finalUrl
        }).success(function(data) {
            deferred.resolve(data);
        }).error(function() {
            deferred.reject('There was an error')
        })
        return deferred.promise;
    }

    return service;
});
<commit_msg>add comment for edification purposes<commit_after>var app = angular.module('myApp', []);

app.controller('myFactoryCtrl', function($scope, myFactory) {
    $scope.data = {};

    $scope.updateMovie = function() {
        myFactory.setMovie($scope.data.movie);
    };

    $scope.submitMovie = function() {
        myFactory.callIomdb()
            .then(function(data) {
              $scope.data.movieData = data;
            }, function(data) {
                alert(data);
            })
    };
});

// Create a Factory in Angular to make the API calls
app.factory('myFactory', function($http, $q) {
    var service = {};
    var baseUrl = 'http://www.omdbapi.com/?t=';
    var _movie = '';
    var _finalUrl = '';

    var makeUrl = function() {
        _movie = _movie.split(' ').join('+');
        _finalUrl = baseUrl + _movie + '&plot=short&r=json'
        return _finalUrl;
    }

    service.setMovie = function(movie) {
        _movie = movie;
    }

    service.getMovie = function() {
        return _movie;
    }

    service.callIomdb = function() {
        makeUrl();
        var deferred = $q.defer();
        $http({
            method: 'GET',
            url: _finalUrl
        }).success(function(data) {
            deferred.resolve(data);
        }).error(function() {
            deferred.reject('There was an error')
        })
        return deferred.promise;
    }

    return service;
});
<|endoftext|>


<commit_before><commit_msg>fixed not being able to ban domains like "x.co"<commit_after><|endoftext|>


<commit_before>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 11/17/12
 * Time: 4:10 PM
 * To change this template use File | Settings | File Templates.
 */

define([
    'modules/controller',
    'modules/page'
], function definePageController(BaseController, BasePage) {

    /**
     * Define page controller
     * @class Controller
     * @mixin {BaseController, BasePage}
     * @constructor
     */
    var Controller = function Controller() {

    };

    return Controller.extend({

        /**
         * Check if allowed to add widget to page
         * @returns {boolean}
         */
        isAllowAddWidget: function isAllowAddWidget() {

            /**
             * Define allow to add widgets
             * @type {boolean}
             */
            var allow = this.model.getConfig('widget').allowToAdd;
            this.scope.logger.debug('Is allowed to add widget?', allow);

            return allow;
        },

        /**
         * Allow to add widget to page
         */
        allowAddWidget: function allowAddWidget() {
            this.scope.logger.debug('Allow to add widget');
            this.model.getConfig('widget').allowToAdd = true;
        },

        /**
         * Do not allow to add widget to page
         */
        banAddWidget: function banAddWidget() {
            this.scope.logger.debug('Do not allow to add widget');
            this.model.getConfig('widget').allowToAdd = false;
        },

        /**
         * Update page height
         */
        updateHeight: function updateHeight() {
            console.log('TODO: Update height');
        },

        /**
         * Get widgets container
         * @returns {*}
         */
        getWidgetsContainer: function getWidgetsContainer() {
            return this.scope.view.elements.$widgets;
        },

        /**
         * Update widget properties
         * @param [item]
         * @returns {boolean}
         */
        updateWidgetsConfig: function updateWidgetsConfig(item) {

            var scope = this.scope,
                items = this.model.getItems(),
                grid = scope.layout.controller.minCellWidth() +
                    scope.layout.config.grid.margin;

            if (scope.layout.config.mode === scope.LAYOUT_MODES.jqUIGrid) {

                if (anthill.base.isDefined(item)) {

                    item.controller.updateDraggable('grid', [grid, grid]);

                    return item;
                }

                for (var index in items) {

                    if (items.hasOwnProperty(index)) {

                        /**
                         * Define widget
                         * @type {*}
                         */
                        var widget = items[index];

                        widget.controller.updateDraggable('grid', [grid, grid]);
                    }
                }
            }
        },

        /**
         * Downgrade widgets layer except widget
         * @param {*} widget
         */
        downgradeLayer: function downgradeLayer(widget) {
            var items = this.model.getItems(),
                item, index;

            for (index in items) {
                if (items.hasOwnProperty(index)) {
                    item = items[index];
                    item.view.elements.$widget._downgradeLayer(50);
                }
            }

            widget.view.elements.$widget._downgradeLayer(51);
        }

    }, BaseController.prototype, BasePage.prototype);
});<commit_msg>add resizable snap to grid<commit_after>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 11/17/12
 * Time: 4:10 PM
 * To change this template use File | Settings | File Templates.
 */

define([
    'modules/controller',
    'modules/page'
], function definePageController(BaseController, BasePage) {

    /**
     * Define page controller
     * @class Controller
     * @mixin {BaseController, BasePage}
     * @constructor
     */
    var Controller = function Controller() {

    };

    return Controller.extend({

        /**
         * Check if allowed to add widget to page
         * @returns {boolean}
         */
        isAllowAddWidget: function isAllowAddWidget() {

            /**
             * Define allow to add widgets
             * @type {boolean}
             */
            var allow = this.model.getConfig('widget').allowToAdd;
            this.scope.logger.debug('Is allowed to add widget?', allow);

            return allow;
        },

        /**
         * Allow to add widget to page
         */
        allowAddWidget: function allowAddWidget() {
            this.scope.logger.debug('Allow to add widget');
            this.model.getConfig('widget').allowToAdd = true;
        },

        /**
         * Do not allow to add widget to page
         */
        banAddWidget: function banAddWidget() {
            this.scope.logger.debug('Do not allow to add widget');
            this.model.getConfig('widget').allowToAdd = false;
        },

        /**
         * Update page height
         */
        updateHeight: function updateHeight() {
            console.log('TODO: Update height');
        },

        /**
         * Get widgets container
         * @returns {*}
         */
        getWidgetsContainer: function getWidgetsContainer() {
            return this.scope.view.elements.$widgets;
        },

        /**
         * Update widget properties
         * @param [item]
         * @returns {boolean}
         */
        updateWidgetsConfig: function updateWidgetsConfig(item) {

            var scope = this.scope,
                items = this.model.getItems(),
                grid = scope.layout.controller.minCellWidth() +
                    scope.layout.config.grid.margin;

            if (scope.layout.config.mode === scope.LAYOUT_MODES.jqUIGrid) {

                if (anthill.base.isDefined(item)) {

                    item.controller.updateDraggable('grid', [grid, grid]);
                    item.controller.updateResizable('grid', grid);

                    return item;
                }

                for (var index in items) {

                    if (items.hasOwnProperty(index)) {

                        /**
                         * Define widget
                         * @type {*}
                         */
                        var widget = items[index];

                        widget.controller.updateDraggable('grid', [grid, grid]);
                        widget.controller.updateResizable('grid', grid);
                    }
                }
            }
        },

        /**
         * Downgrade widgets layer except widget
         * @param {*} widget
         */
        downgradeLayer: function downgradeLayer(widget) {
            var items = this.model.getItems(),
                item, index;

            for (index in items) {
                if (items.hasOwnProperty(index)) {
                    item = items[index];
                    item.view.elements.$widget._downgradeLayer(50);
                }
            }

            widget.view.elements.$widget._downgradeLayer(51);
        }

    }, BaseController.prototype, BasePage.prototype);
});<|endoftext|>


<commit_before>define(function(require, exports, module) {
"use strict";

var modes = [];
/**
 * Suggests a mode based on the file extension present in the given path
 * @param {string} path The path to the file
 * @returns {object} Returns an object containing information about the
 *  suggested mode.
 */
function getModeForPath(path) {
    var mode = modesByName.text;
    var fileName = path.split(/[\/\\]/).pop();
    for (var i = 0; i < modes.length; i++) {
        if (modes[i].supportsFile(fileName)) {
            mode = modes[i];
            break;
        }
    }
    return mode;
}

var Mode = function(name, caption, extensions) {
    this.name = name;
    this.caption = caption;
    this.mode = "ace/mode/" + name;
    this.extensions = extensions;
    var re;
    if (/\^/.test(extensions)) {
        re = extensions.replace(/\|(\^)?/g, function(a, b){
            return "$|" + (b ? "^" : "^.*\\.");
        }) + "$";
    } else {
        re = "^.*\\.(" + extensions + ")$";
    }

    this.extRe = new RegExp(re, "gi");
};

Mode.prototype.supportsFile = function(filename) {
    return filename.match(this.extRe);
};

// todo firstlinematch
var supportedModes = {
    ABAP:        ["abap"],
    ABC:         ["abc"],
    ActionScript:["as"],
    ADA:         ["ada|adb"],
    Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"],
    AsciiDoc:    ["asciidoc|adoc"],
    Assembly_x86:["asm|a"],
    AutoHotKey:  ["ahk"],
    BatchFile:   ["bat|cmd"],
    Bro:         ["bro"],
    C_Cpp:       ["cpp|c|cc|cxx|h|hh|hpp|ino"],
    C9Search:    ["c9search_results"],
    Cirru:       ["cirru|cr"],
    Clojure:     ["clj|cljs"],
    Cobol:       ["CBL|COB"],
    coffee:      ["coffee|cf|cson|^Cakefile"],
    ColdFusion:  ["cfm"],
    CSharp:      ["cs"],
    CSS:         ["css"],
    Curly:       ["curly"],
    D:           ["d|di"],
    Dart:        ["dart"],
    Diff:        ["diff|patch"],
    Dockerfile:  ["^Dockerfile"],
    Dot:         ["dot"],
    Drools:      ["drl"],
    Dummy:       ["dummy"],
    DummySyntax: ["dummy"],
    Eiffel:      ["e|ge"],
    EJS:         ["ejs"],
    Elixir:      ["ex|exs"],
    Elm:         ["elm"],
    Erlang:      ["erl|hrl"],
    Forth:       ["frt|fs|ldr|fth|4th"],
    Fortran:     ["f|f90"],
    FTL:         ["ftl"],
    Gcode:       ["gcode"],
    Gherkin:     ["feature"],
    Gitignore:   ["^.gitignore"],
    Glsl:        ["glsl|frag|vert"],
    Gobstones:   ["gbs"],
    golang:      ["go"],
    Groovy:      ["groovy"],
    HAML:        ["haml"],
    Handlebars:  ["hbs|handlebars|tpl|mustache"],
    Haskell:     ["hs"],
    Haskell_Cabal:     ["cabal"],
    haXe:        ["hx"],
    Hjson:       ["hjson"],
    HTML:        ["html|htm|xhtml"],
    HTML_Elixir: ["eex|html.eex"],
    HTML_Ruby:   ["erb|rhtml|html.erb"],
    INI:         ["ini|conf|cfg|prefs"],
    Io:          ["io"],
    Jack:        ["jack"],
    Jade:        ["jade"],
    Java:        ["java"],
    JavaScript:  ["js|jsm|jsx"],
    JSON:        ["json"],
    JSONiq:      ["jq"],
    JSP:         ["jsp"],
    JSX:         ["jsx"],
    Julia:       ["jl"],
    Kotlin:      ["kt|kts"],
    LaTeX:       ["tex|latex|ltx|bib"],
    LESS:        ["less"],
    Liquid:      ["liquid"],
    Lisp:        ["lisp"],
    LiveScript:  ["ls"],
    LogiQL:      ["logic|lql"],
    LSL:         ["lsl"],
    Lua:         ["lua"],
    LuaPage:     ["lp"],
    Lucene:      ["lucene"],
    Makefile:    ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"],
    Markdown:    ["md|markdown"],
    Mask:        ["mask"],
    MATLAB:      ["matlab"],
    Maze:        ["mz"],
    MEL:         ["mel"],
    MUSHCode:    ["mc|mush"],
    MySQL:       ["mysql"],
    Nix:         ["nix"],
    NSIS:        ["nsi|nsh"],
    ObjectiveC:  ["m|mm"],
    OCaml:       ["ml|mli"],
    Pascal:      ["pas|p"],
    Perl:        ["pl|pm"],
    pgSQL:       ["pgsql"],
    PHP:         ["php|phtml|shtml|php3|php4|php5|phps|phpt|aw|ctp|module"],
    Powershell:  ["ps1"],
    Praat:       ["praat|praatscript|psc|proc"],
    Prolog:      ["plg|prolog"],
    Properties:  ["properties"],
    Protobuf:    ["proto"],
    Python:      ["py"],
    R:           ["r"],
    Razor:       ["cshtml|asp"],
    RDoc:        ["Rd"],
    RHTML:       ["Rhtml"],
    RST:         ["rst"],
    Ruby:        ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"],
    Rust:        ["rs"],
    SASS:        ["sass"],
    SCAD:        ["scad"],
    Scala:       ["scala"],
    Scheme:      ["scm|sm|rkt|oak|scheme"],
    SCSS:        ["scss"],
    SH:          ["sh|bash|^.bashrc"],
    SJS:         ["sjs"],
    Smarty:      ["smarty|tpl"],
    snippets:    ["snippets"],
    Soy_Template:["soy"],
    Space:       ["space"],
    SQL:         ["sql"],
    SQLServer:   ["sqlserver"],
    Stylus:      ["styl|stylus"],
    SVG:         ["svg"],
    Swift:       ["swift"],
    Tcl:         ["tcl"],
    Tex:         ["tex"],
    Text:        ["txt"],
    Textile:     ["textile"],
    Toml:        ["toml"],
    TSX:         ["tsx"],
    Twig:        ["twig|swig"],
    Typescript:  ["ts|typescript|str"],
    Vala:        ["vala"],
    VBScript:    ["vbs|vb"],
    Velocity:    ["vm"],
    Verilog:     ["v|vh|sv|svh"],
    VHDL:        ["vhd|vhdl"],
    Wollok:      ["wlk|wpgm|wtest"],
    XML:         ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|xaml"],
    XQuery:      ["xq"],
    YAML:        ["yaml|yml"],
    // Add the missing mode "Django" to ext-modelist
    Django:      ["html"]
};

var nameOverrides = {
    ObjectiveC: "Objective-C",
    CSharp: "C#",
    golang: "Go",
    C_Cpp: "C and C++",
    coffee: "CoffeeScript",
    HTML_Ruby: "HTML (Ruby)",
    HTML_Elixir: "HTML (Elixir)",
    FTL: "FreeMarker"
};
var modesByName = {};
for (var name in supportedModes) {
    var data = supportedModes[name];
    var displayName = (nameOverrides[name] || name).replace(/_/g, " ");
    var filename = name.toLowerCase();
    var mode = new Mode(filename, displayName, data[0]);
    modesByName[filename] = mode;
    modes.push(mode);
}

module.exports = {
    getModeForPath: getModeForPath,
    modes: modes,
    modesByName: modesByName
};

});

<commit_msg>Update modelist.js<commit_after>define(function(require, exports, module) {
"use strict";

var modes = [];
/**
 * Suggests a mode based on the file extension present in the given path
 * @param {string} path The path to the file
 * @returns {object} Returns an object containing information about the
 *  suggested mode.
 */
function getModeForPath(path) {
    var mode = modesByName.text;
    var fileName = path.split(/[\/\\]/).pop();
    for (var i = 0; i < modes.length; i++) {
        if (modes[i].supportsFile(fileName)) {
            mode = modes[i];
            break;
        }
    }
    return mode;
}

var Mode = function(name, caption, extensions) {
    this.name = name;
    this.caption = caption;
    this.mode = "ace/mode/" + name;
    this.extensions = extensions;
    var re;
    if (/\^/.test(extensions)) {
        re = extensions.replace(/\|(\^)?/g, function(a, b){
            return "$|" + (b ? "^" : "^.*\\.");
        }) + "$";
    } else {
        re = "^.*\\.(" + extensions + ")$";
    }

    this.extRe = new RegExp(re, "gi");
};

Mode.prototype.supportsFile = function(filename) {
    return filename.match(this.extRe);
};

// todo firstlinematch
var supportedModes = {
    ABAP:        ["abap"],
    ABC:         ["abc"],
    ActionScript:["as"],
    ADA:         ["ada|adb"],
    Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"],
    AsciiDoc:    ["asciidoc|adoc"],
    Assembly_x86:["asm|a"],
    AutoHotKey:  ["ahk"],
    BatchFile:   ["bat|cmd"],
    Bro:         ["bro"],
    C_Cpp:       ["cpp|c|cc|cxx|h|hh|hpp|ino"],
    C9Search:    ["c9search_results"],
    Cirru:       ["cirru|cr"],
    Clojure:     ["clj|cljs"],
    Cobol:       ["CBL|COB"],
    coffee:      ["coffee|cf|cson|^Cakefile"],
    ColdFusion:  ["cfm"],
    CSharp:      ["cs"],
    CSS:         ["css"],
    Curly:       ["curly"],
    D:           ["d|di"],
    Dart:        ["dart"],
    Diff:        ["diff|patch"],
    Dockerfile:  ["^Dockerfile"],
    Dot:         ["dot"],
    Drools:      ["drl"],
    Dummy:       ["dummy"],
    DummySyntax: ["dummy"],
    Eiffel:      ["e|ge"],
    EJS:         ["ejs"],
    Elixir:      ["ex|exs"],
    Elm:         ["elm"],
    Erlang:      ["erl|hrl"],
    Forth:       ["frt|fs|ldr|fth|4th"],
    Fortran:     ["f|f90"],
    FTL:         ["ftl"],
    Gcode:       ["gcode"],
    Gherkin:     ["feature"],
    Gitignore:   ["^.gitignore"],
    Glsl:        ["glsl|frag|vert"],
    Gobstones:   ["gbs"],
    golang:      ["go"],
    Groovy:      ["groovy"],
    HAML:        ["haml"],
    Handlebars:  ["hbs|handlebars|tpl|mustache"],
    Haskell:     ["hs"],
    Haskell_Cabal:     ["cabal"],
    haXe:        ["hx"],
    Hjson:       ["hjson"],
    HTML:        ["html|htm|xhtml"],
    HTML_Elixir: ["eex|html.eex"],
    HTML_Ruby:   ["erb|rhtml|html.erb"],
    INI:         ["ini|conf|cfg|prefs"],
    Io:          ["io"],
    Jack:        ["jack"],
    Jade:        ["jade|pug"],
    Java:        ["java"],
    JavaScript:  ["js|jsm|jsx"],
    JSON:        ["json"],
    JSONiq:      ["jq"],
    JSP:         ["jsp"],
    JSX:         ["jsx"],
    Julia:       ["jl"],
    Kotlin:      ["kt|kts"],
    LaTeX:       ["tex|latex|ltx|bib"],
    LESS:        ["less"],
    Liquid:      ["liquid"],
    Lisp:        ["lisp"],
    LiveScript:  ["ls"],
    LogiQL:      ["logic|lql"],
    LSL:         ["lsl"],
    Lua:         ["lua"],
    LuaPage:     ["lp"],
    Lucene:      ["lucene"],
    Makefile:    ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"],
    Markdown:    ["md|markdown"],
    Mask:        ["mask"],
    MATLAB:      ["matlab"],
    Maze:        ["mz"],
    MEL:         ["mel"],
    MUSHCode:    ["mc|mush"],
    MySQL:       ["mysql"],
    Nix:         ["nix"],
    NSIS:        ["nsi|nsh"],
    ObjectiveC:  ["m|mm"],
    OCaml:       ["ml|mli"],
    Pascal:      ["pas|p"],
    Perl:        ["pl|pm"],
    pgSQL:       ["pgsql"],
    PHP:         ["php|phtml|shtml|php3|php4|php5|phps|phpt|aw|ctp|module"],
    Powershell:  ["ps1"],
    Praat:       ["praat|praatscript|psc|proc"],
    Prolog:      ["plg|prolog"],
    Properties:  ["properties"],
    Protobuf:    ["proto"],
    Python:      ["py"],
    R:           ["r"],
    Razor:       ["cshtml|asp"],
    RDoc:        ["Rd"],
    RHTML:       ["Rhtml"],
    RST:         ["rst"],
    Ruby:        ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"],
    Rust:        ["rs"],
    SASS:        ["sass"],
    SCAD:        ["scad"],
    Scala:       ["scala"],
    Scheme:      ["scm|sm|rkt|oak|scheme"],
    SCSS:        ["scss"],
    SH:          ["sh|bash|^.bashrc"],
    SJS:         ["sjs"],
    Smarty:      ["smarty|tpl"],
    snippets:    ["snippets"],
    Soy_Template:["soy"],
    Space:       ["space"],
    SQL:         ["sql"],
    SQLServer:   ["sqlserver"],
    Stylus:      ["styl|stylus"],
    SVG:         ["svg"],
    Swift:       ["swift"],
    Tcl:         ["tcl"],
    Tex:         ["tex"],
    Text:        ["txt"],
    Textile:     ["textile"],
    Toml:        ["toml"],
    TSX:         ["tsx"],
    Twig:        ["twig|swig"],
    Typescript:  ["ts|typescript|str"],
    Vala:        ["vala"],
    VBScript:    ["vbs|vb"],
    Velocity:    ["vm"],
    Verilog:     ["v|vh|sv|svh"],
    VHDL:        ["vhd|vhdl"],
    Wollok:      ["wlk|wpgm|wtest"],
    XML:         ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|xaml"],
    XQuery:      ["xq"],
    YAML:        ["yaml|yml"],
    // Add the missing mode "Django" to ext-modelist
    Django:      ["html"]
};

var nameOverrides = {
    ObjectiveC: "Objective-C",
    CSharp: "C#",
    golang: "Go",
    C_Cpp: "C and C++",
    coffee: "CoffeeScript",
    HTML_Ruby: "HTML (Ruby)",
    HTML_Elixir: "HTML (Elixir)",
    FTL: "FreeMarker"
};
var modesByName = {};
for (var name in supportedModes) {
    var data = supportedModes[name];
    var displayName = (nameOverrides[name] || name).replace(/_/g, " ");
    var filename = name.toLowerCase();
    var mode = new Mode(filename, displayName, data[0]);
    modesByName[filename] = mode;
    modes.push(mode);
}

module.exports = {
    getModeForPath: getModeForPath,
    modes: modes,
    modesByName: modesByName
};

});

<|endoftext|>