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

/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, brackets, $, Image, document, require, Mustache, window */

require.config({
    paths: {
        "text" : "lib/text",
        "i18n" : "lib/i18n"
    },
    locale: brackets.getLocale()
});

define(function (require, exports, module) {
	"use strict";
	var BUTTON_CMD = "urlimage.convertit",
        CONTEXT_CMD = "getimage.convertit";

	// Brackets modules
	var AppInit				= brackets.getModule("utils/AppInit"),
		EditorManager       = brackets.getModule("editor/EditorManager"),
		ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
		DocumentManager     = brackets.getModule("document/DocumentManager"),
		CommandManager      = brackets.getModule("command/CommandManager"),
		KeyBindingManager   = brackets.getModule("command/KeyBindingManager"),
        ProjectManager      = brackets.getModule("project/ProjectManager"),
		Menus				= brackets.getModule("command/Menus"),
		Dialogs             = brackets.getModule("widgets/Dialogs"),
		Strings             = brackets.getModule("strings");

    var projectMenu         = Menus.getContextMenu(Menus.ContextMenuIds.PROJECT_MENU);

	// local modules
	var mainDialog		= require("text!html/itd-dialog.html"),
		idtToolbarHtml	= require("text!html/itd-toolbar.html");

	var Trad             = require("strings");

	var $toolbarIcon	= $(idtToolbarHtml),
		$mainDialog,
        localURL,
        dataURL;

	function loadImage(imgUrl, $getBodyControl) {
		// The convert to data trick
		var imgee = new Image();
		imgee.src = imgUrl;
		imgee.onload = function () {

			var canvas = document.createElement("canvas");
			canvas.width = this.width;
			canvas.height = this.height;

			var ctx = canvas.getContext("2d");
			ctx.drawImage(this, 0, 0);

			var dataURL = canvas.toDataURL("image/png");
			// Finally showing the result
			$getBodyControl.html(Trad.COPY_THAT + " :
<textarea class='data'>" + dataURL + "</textarea>
" + Trad.IMAGE_CONV + " :
");
		};
	}

    function convertToData(imgUrl) {
		// The convert to data trick
		var imgee = new Image();
		imgee.src = imgUrl;
		imgee.onload = function () {

			var canvas = document.createElement("canvas");
			canvas.width = this.width;
			canvas.height = this.height;

			var ctx = canvas.getContext("2d");
			ctx.drawImage(this, 0, 0);

			dataURL = canvas.toDataURL("image/png");

            $('body').trigger('convertCompleted');

        };
    }

    function showData(data, imgUrl, $getBodyControl) {

        // Finally showing the result
        $getBodyControl.html(Trad.COPY_THAT + " :
<textarea class='data'>" + data + "</textarea>
" + Trad.IMAGE_CONV + " :
");
        $getBodyControl.find(".data").focus();
    }

/*    Functions used when right clicking an image in the project bar */

    // determine if a file is an image that can be convert
    // parameter : entry - the current file entry object containing the file name
    function determineFileType(fileEntry) {
        if (fileEntry && fileEntry.fullPath && fileEntry.fullPath.match(/\.png$|.jpg$|.gif$/)) {
            return "image";
        } else {
            return "unknown";
        }
    }

    // Removes menu item
    function cleanMenu(menu) {
        menu.removeMenuItem(CONTEXT_CMD);
    }

    //adds a menuitem to a menu if the current file matches a known type
    //parameters: menu - the context menu or working files menu
    //           entry - the current file entry object containing the file name

    function checkFileTypes(menu, entry) {
        if (entry === null) {
            return "unknown";
        }
        var type = determineFileType(entry);
        if (type === "image") {
            menu.addMenuItem(CONTEXT_CMD, "", Menus.LAST);
        }
    }

    // check if the extension should add a menu item to the project menu (under the project name, left panel)
    $(projectMenu).on("beforeContextMenuOpen", function (evt) {
        var selectedEntry = ProjectManager.getSelectedItem(),
            text = '';
        if (selectedEntry && selectedEntry.fullPath && DocumentManager.getCurrentDocument() !== null && selectedEntry.fullPath === DocumentManager.getCurrentDocument().file.fullPath) {
            text = DocumentManager.getCurrentDocument().getText();
        }
        cleanMenu(projectMenu);
        localURL = selectedEntry.fullPath;
        checkFileTypes(projectMenu, selectedEntry, text);
    });

/*    Functions used when clicking the extention button */

//    Create dynamic path for local files
    function localPath(img) {
        return window.URL.createObjectURL(img);
    }

//    Open the dialog box and initialize the elements
	function openConvertDialog() {

		var $dlg,
			$getUrlControl,
            $getLocalUrlControl,
            $getLocalLabel,
			$getBodyControl;

		$dlg = $mainDialog;

		Dialogs.showModalDialogUsingTemplate($dlg);

		// URL input
		$getUrlControl = $dlg.find(".get-url");
		$getUrlControl.focus();

        // File input
        $getLocalUrlControl = $dlg.find(".get-local");
        $getLocalLabel = $dlg.find("[for='get-local']");
        $getLocalUrlControl.change(function () {
            var image = this.files[0];
            $getLocalLabel.html(image.name);
            $getUrlControl.html("");
        });

		// ModalBody
		$getBodyControl = $dlg.find(".data-show");

		// add OK button handler
		$dlg.on("click", ".dialog-button-ext", function () {
			$getBodyControl.empty();
			var imgUrl = $getUrlControl.val() || localPath($getLocalUrlControl[0].files[0]) || "";
			// Ready ? Let's go !
			if (imgUrl !== "") {
				loadImage(imgUrl, $getBodyControl);
			}
		});

        return $dlg;
	}

    // Launch the extension to directly return the data URI of the selected image
    function convertFromTree() {
        var $dlg = openConvertDialog();
        convertToData(localURL);
        $('body').on('convertCompleted', function () {
            showData(dataURL, localURL, $dlg.find(".data-show"));
        });
    }

	// load everything when brackets is done loading
	AppInit.appReady(function () {
		$toolbarIcon.appendTo("#main-toolbar .buttons");
		$toolbarIcon.on('click', openConvertDialog);
		// CSS
		ExtensionUtils.loadStyleSheet(module, "style/style.css");
	});

	CommandManager.register(Trad.COMMAND_NAME, BUTTON_CMD, openConvertDialog);
	CommandManager.register(Trad.COMMAND_NAME, CONTEXT_CMD, convertFromTree);
	KeyBindingManager.addBinding(BUTTON_CMD, "Alt-Shift-G");

	var menu = Menus.getMenu(Menus.AppMenuBar.NAVIGATE_MENU);
	menu.addMenuItem(BUTTON_CMD);

	$mainDialog = $(Mustache.render(mainDialog, Trad));

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

/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, brackets, $, Image, document, require, Mustache, window */

require.config({
    paths: {
        "text" : "lib/text",
        "i18n" : "lib/i18n"
    },
    locale: brackets.getLocale()
});

define(function (require, exports, module) {
	"use strict";
	var BUTTON_CMD = "urlimage.convertit",
        CONTEXT_CMD = "getimage.convertit";

	// Brackets modules
	var AppInit				= brackets.getModule("utils/AppInit"),
		EditorManager       = brackets.getModule("editor/EditorManager"),
		ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
		DocumentManager     = brackets.getModule("document/DocumentManager"),
		CommandManager      = brackets.getModule("command/CommandManager"),
		KeyBindingManager   = brackets.getModule("command/KeyBindingManager"),
        ProjectManager      = brackets.getModule("project/ProjectManager"),
		Menus				= brackets.getModule("command/Menus"),
		Dialogs             = brackets.getModule("widgets/Dialogs"),
		Strings             = brackets.getModule("strings");

    var projectMenu         = Menus.getContextMenu(Menus.ContextMenuIds.PROJECT_MENU);

	// local modules
	var mainDialog		= require("text!html/itd-dialog.html"),
		idtToolbarHtml	= require("text!html/itd-toolbar.html");

	var Trad             = require("strings");

	var $toolbarIcon	= $(idtToolbarHtml),
		$mainDialog,
        localURL,
        dataURL;

	function loadImage(imgUrl, $getBodyControl) {
		// The convert to data trick
		var imgee = new Image();
		imgee.src = imgUrl;
		imgee.onload = function () {

			var canvas = document.createElement("canvas");
			canvas.width = this.width;
			canvas.height = this.height;

			var ctx = canvas.getContext("2d");
			ctx.drawImage(this, 0, 0);

			var dataURL = canvas.toDataURL("image/png");
			// Finally showing the result
			$getBodyControl.html(Trad.COPY_THAT + " :
<textarea class='data'>" + dataURL + "</textarea>
" + Trad.IMAGE_CONV + " :
");
		};
	}

    function convertToData(imgUrl) {
		// The convert to data trick
		var imgee = new Image();
		imgee.src = imgUrl;
		imgee.onload = function () {

			var canvas = document.createElement("canvas");
			canvas.width = this.width;
			canvas.height = this.height;

			var ctx = canvas.getContext("2d");
			ctx.drawImage(this, 0, 0);

			dataURL = canvas.toDataURL("image/png");

            $('body').trigger('convertCompleted');

        };
    }

    function showData(data, imgUrl, $getBodyControl) {

        // Finally showing the result
        $getBodyControl.html(Trad.COPY_THAT + " :
<textarea class='data'>" + data + "</textarea>
" + Trad.IMAGE_CONV + " :
");
        $getBodyControl.find(".data").focus();
    }

/*    Functions used when right clicking an image in the project bar */

    // determine if a file is an image that can be convert
    // parameter : entry - the current file entry object containing the file name
    function determineFileType(fileEntry) {
        if (fileEntry && fileEntry.fullPath && fileEntry.fullPath.match(/\.png$|.jpg$|.gif$/)) {
            return "image";
        } else {
            return "unknown";
        }
    }

    // Removes menu item
    function cleanMenu(menu) {
        menu.removeMenuItem(CONTEXT_CMD);
    }

    //adds a menuitem to a menu if the current file matches a known type
    //parameters: menu - the context menu or working files menu
    //           entry - the current file entry object containing the file name

    function checkFileTypes(menu, entry) {
        if (entry === null) {
            return "unknown";
        }
        var type = determineFileType(entry);
        if (type === "image") {
            menu.addMenuItem(CONTEXT_CMD, "", Menus.LAST);
        }
    }

    // check if the extension should add a menu item to the project menu (under the project name, left panel)
    projectMenu.on("beforeContextMenuOpen", function (evt) {
        var selectedEntry = ProjectManager.getSelectedItem(),
            text = '';
        if (selectedEntry && selectedEntry.fullPath && DocumentManager.getCurrentDocument() !== null && selectedEntry.fullPath === DocumentManager.getCurrentDocument().file.fullPath) {
            text = DocumentManager.getCurrentDocument().getText();
        }
        cleanMenu(projectMenu);
        localURL = selectedEntry.fullPath;
        checkFileTypes(projectMenu, selectedEntry, text);
    });

/*    Functions used when clicking the extention button */

//    Create dynamic path for local files
    function localPath(img) {
        return window.URL.createObjectURL(img);
    }

//    Open the dialog box and initialize the elements
	function openConvertDialog() {

		var $dlg,
			$getUrlControl,
            $getLocalUrlControl,
            $getLocalLabel,
			$getBodyControl;

		$dlg = $mainDialog;

		Dialogs.showModalDialogUsingTemplate($dlg);

		// URL input
		$getUrlControl = $dlg.find(".get-url");
		$getUrlControl.focus();

        // File input
        $getLocalUrlControl = $dlg.find(".get-local");
        $getLocalLabel = $dlg.find("[for='get-local']");
        $getLocalUrlControl.change(function () {
            var image = this.files[0];
            $getLocalLabel.html(image.name);
            $getUrlControl.html("");
        });

		// ModalBody
		$getBodyControl = $dlg.find(".data-show");

		// add OK button handler
		$dlg.on("click", ".dialog-button-ext", function () {
			$getBodyControl.empty();
			var imgUrl = $getUrlControl.val() || localPath($getLocalUrlControl[0].files[0]) || "";
			// Ready ? Let's go !
			if (imgUrl !== "") {
				loadImage(imgUrl, $getBodyControl);
			}
		});

        return $dlg;
	}

    // Launch the extension to directly return the data URI of the selected image
    function convertFromTree() {
        var $dlg = openConvertDialog();
        convertToData(localURL);
        $('body').on('convertCompleted', function () {
            showData(dataURL, localURL, $dlg.find(".data-show"));
        });
    }

	// load everything when brackets is done loading
	AppInit.appReady(function () {
		$toolbarIcon.appendTo("#main-toolbar .buttons");
		$toolbarIcon.on('click', openConvertDialog);
		// CSS
		ExtensionUtils.loadStyleSheet(module, "style/style.css");
	});

	CommandManager.register(Trad.COMMAND_NAME, BUTTON_CMD, openConvertDialog);
	CommandManager.register(Trad.COMMAND_NAME, CONTEXT_CMD, convertFromTree);
	KeyBindingManager.addBinding(BUTTON_CMD, "Alt-Shift-G");

	var menu = Menus.getMenu(Menus.AppMenuBar.NAVIGATE_MENU);
	menu.addMenuItem(BUTTON_CMD);

	$mainDialog = $(Mustache.render(mainDialog, Trad));

});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path-posix');
var mkdirp = require('mkdirp');
var walkSync = require('walk-sync');
var Minimatch = require('minimatch').Minimatch;
var arrayEqual = require('array-equal');
var Plugin = require('broccoli-plugin');
var symlinkOrCopy = require('symlink-or-copy');
var debug = require('debug');
var FSTree = require('fs-tree-diff');
var rimraf = require('rimraf');
var BlankObject = require('blank-object');
var heimdall = require('heimdalljs');

function ApplyPatchesSchema() {
  this.mkdir = 0;
  this.rmdir = 0;
  this.unlink = 0;
  this.change = 0;
  this.create = 0;
  this.other = 0;
  this.processed = 0;
  this.linked = 0;
}

function makeDictionary() {
  var cache = new BlankObject();

  cache['_dict'] = null;
  delete cache['_dict'];
  return cache;
}
// copied mostly from node-glob cc @isaacs
function isNotAPattern(pattern) {
  var set = new Minimatch(pattern).set;
  if (set.length > 1) {
    return false;
  }

  for (var j = 0; j < set[0].length; j++) {
    if (typeof set[0][j] !== 'string') {
      return false;
    }
  }

  return true;
}

Funnel.prototype = Object.create(Plugin.prototype);
Funnel.prototype.constructor = Funnel;
function Funnel(inputNode, options) {
  if (!(this instanceof Funnel)) { return new Funnel(inputNode, options); }

  Plugin.call(this, [inputNode], options);

  this._persistentOutput = true;

  this._includeFileCache = makeDictionary();
  this._destinationPathCache = makeDictionary();
  this._currentTree = new FSTree();
  this._lastInputPath = null;

  var keys = Object.keys(options || {});
  for (var i = 0, l = keys.length; i < l; i++) {
    var key = keys[i];
    this[key] = options[key];
  }

  this.destDir = this.destDir || '/';
  this.count = 0;

  if (this.files && typeof this.files === 'function') {
    // Save dynamic files func as a different variable and let the rest of the code
    // still assume that this.files is always an array.
    this._dynamicFilesFunc = this.files;
    delete this.files;
  } else if (this.files && !Array.isArray(this.files)) {
    throw new Error('Invalid files option, it must be an array or function (that returns an array).');
  }

  if ((this.files || this._dynamicFilesFunc) && (this.include || this.exclude)) {
    throw new Error('Cannot pass files option (array or function) and a include/exlude filter. You can only have one or the other');
  }

  if (this.files) {
    if (this.files.filter(isNotAPattern).length !== this.files.length) {
      console.warn('broccoli-funnel does not support `files:` option with globs, please use `include:` instead');
      this.include = this.files;
      this.files = undefined;
    }
  }

  this._setupFilter('include');
  this._setupFilter('exclude');

  this._matchedWalk = this.include && this.include.filter(function(a) {
    return a instanceof Minimatch;
  }).length === this.include.length;

  this._instantiatedStack = (new Error()).stack;
  this._buildStart = undefined;
}

Funnel.prototype._debugName = function() {
  return this.description || this._annotation || this.name || this.constructor.name;
};

Funnel.prototype._debug = function(message) {
  debug('broccoli-funnel:' + (this._debugName())).apply(null, arguments);
};

Funnel.prototype._setupFilter = function(type) {
  if (!this[type]) {
    return;
  }

  if (!Array.isArray(this[type])) {
    throw new Error('Invalid ' + type + ' option, it must be an array. You specified `' + typeof this[type] + '`.');
  }

  // Clone the filter array so we are not mutating an external variable
  var filters = this[type] = this[type].slice(0);

  for (var i = 0, l = filters.length; i < l; i++) {
    filters[i] = this._processPattern(filters[i]);
  }
};

Funnel.prototype._processPattern = function(pattern) {
  if (pattern instanceof RegExp) {
    return pattern;
  }

  var type = typeof pattern;

  if (type === 'string') {
    return new Minimatch(pattern);
  }

  if (type === 'function') {
    return pattern;
  }

  throw new Error('include/exclude patterns can be a RegExp, glob string, or function. You supplied `' + typeof pattern +'`.');
};

Funnel.prototype.shouldLinkRoots = function() {
  return !this.files && !this.include && !this.exclude && !this.getDestinationPath;
};

Funnel.prototype.build = function() {
  this._buildStart = new Date();
  this.destPath = path.join(this.outputPath, this.destDir);

  if (this.destPath[this.destPath.length -1] === '/') {
    this.destPath = this.destPath.slice(0, -1);
  }

  var inputPath = this.inputPaths[0];
  if (this.srcDir) {
    inputPath = path.join(inputPath, this.srcDir);
  }

  if (this._dynamicFilesFunc) {
    this.lastFiles = this.files;
    this.files = this._dynamicFilesFunc() || [];

    // Blow away the include cache if the list of files is new
    if (this.lastFiles !== undefined && !arrayEqual(this.lastFiles, this.files)) {
      this._includeFileCache = makeDictionary();
    }
  }

  var linkedRoots = false;
  if (this.shouldLinkRoots()) {
    linkedRoots = true;

    var inputPathExist = fs.existsSync(inputPath);

    if (this._lastInputPath ? !inputPathExist : inputPathExist) {
      rimraf.sync(this.outputPath);

      if (inputPathExist) {
        this._copy(inputPath, this.destPath);
      }
    }

    this._lastInputPath = inputPath;
  } else {
    this.processFilters(inputPath);
  }

  this._debug('build, %o', {
    in: new Date() - this._buildStart + 'ms',
    linkedRoots: linkedRoots,
    inputPath: inputPath,
    destPath: this.destPath
  });
};

function ensureRelative(string) {
  if (string.charAt(0) === '/') {
    return string.substring(1);
  }
  return string;
}

Funnel.prototype._processEntries = function(entries) {
  return entries.filter(function(entry) {
    // support the second set of filters walk-sync does not support
    //   * regexp
    //   * excludes
    return this.includeFile(entry.relativePath);
  }, this).map(function(entry) {

    var relativePath = entry.relativePath;

    entry.relativePath = this.lookupDestinationPath(relativePath);

    this.outputToInputMappings[entry.relativePath] = relativePath;

    return entry;
  }, this);
};

Funnel.prototype._processPaths  = function(paths) {
  return paths.
    slice(0).
    filter(this.includeFile, this).
    map(function(relativePath) {
      var output = this.lookupDestinationPath(relativePath);
      this.outputToInputMappings[output] = relativePath;
      return output;
    }, this);
};

Funnel.prototype.processFilters = function(inputPath) {
  var nextTree;

  var instrumentation = heimdall.start('derivePatches');
  var entries;

  this.outputToInputMappings = {}; // we allow users to rename files

  if (this.files && !this.exclude && !this.include) {
    entries = this._processPaths(this.files);
    // clone to be compatible with walkSync
    nextTree = FSTree.fromPaths(entries, { sortAndExpand: true });
  } else {

    if (this._matchedWalk) {
      entries = walkSync.entries(inputPath, this.include);
    } else {
      entries = walkSync.entries(inputPath);
    }

    entries = this._processEntries(entries);
    nextTree = FSTree.fromEntries(entries, { sortAndExpand: true });
  }

  var patches = this._currentTree.calculatePatch(nextTree);

  this._currentTree = nextTree;

  instrumentation.stats.patches = patches.length;
  instrumentation.stats.entries = entries.length;

  var outputPath = this.outputPath;

  instrumentation.stop();

  instrumentation = heimdall.start('applyPatch', ApplyPatchesSchema);

  patches.forEach(function(entry) {
    this._applyPatch(entry, inputPath, outputPath, instrumentation.stats);
  }, this);

  instrumentation.stop();
};

Funnel.prototype._applyPatch = function applyPatch(entry, inputPath, _outputPath, stats) {
  var outputToInput = this.outputToInputMappings;
  var operation = entry[0];
  var outputRelative = entry[1];

  if (!outputRelative) {
    // broccoli itself maintains the roots, we can skip any operation on them
    return;
  }

  var outputPath = _outputPath + '/' + outputRelative;

  this._debug('%s %s', operation, outputPath);

  switch (operation) {
    case 'unlink' :
      stats.unlink++;

      fs.unlinkSync(outputPath);
      break;
    case 'rmdir'  :
      stats.rmdir++;
      fs.rmdirSync(outputPath);
      break;
    case 'mkdir'  :
      stats.mkdir++;
      fs.mkdirSync(outputPath);
      break;
    case 'change':
      stats.change++;
      /* falls through */
    case 'create':
      if (operation === 'create') {
        stats.create++;
      }

      var relativePath = outputToInput[outputRelative];
      if (relativePath === undefined) {
        relativePath = outputToInput['/' + outputRelative];
      }
      this.processFile(inputPath + '/' + relativePath, outputPath, relativePath);
      break;
    default: throw new Error('Unknown operation: ' + operation);
  }
};

Funnel.prototype.lookupDestinationPath = function(relativePath) {
  if (this._destinationPathCache[relativePath] !== undefined) {
    return this._destinationPathCache[relativePath];
  }

  // the destDir is absolute to prevent '..' above the output dir
  if (this.getDestinationPath) {
    return this._destinationPathCache[relativePath] = ensureRelative(path.join(this.destDir, this.getDestinationPath(relativePath)));
  }

  return this._destinationPathCache[relativePath] = ensureRelative(path.join(this.destDir, relativePath));
};

Funnel.prototype.includeFile = function(relativePath) {
  var includeFileCache = this._includeFileCache;

  if (includeFileCache[relativePath] !== undefined) {
    return includeFileCache[relativePath];
  }

  // do not include directories, only files
  if (relativePath[relativePath.length - 1] === '/') {
    return includeFileCache[relativePath] = false;
  }

  var i, l, pattern;

  // Check for specific files listing
  if (this.files) {
    return includeFileCache[relativePath] = this.files.indexOf(relativePath) > -1;
  }

  // Check exclude patterns
  if (this.exclude) {
    for (i = 0, l = this.exclude.length; i < l; i++) {
      // An exclude pattern that returns true should be ignored
      pattern = this.exclude[i];

      if (this._matchesPattern(pattern, relativePath)) {
        return includeFileCache[relativePath] = false;
      }
    }
  }

  // Check include patterns
  if (this.include && this.include.length > 0) {
    for (i = 0, l = this.include.length; i < l; i++) {
      // An include pattern that returns true (and wasn't excluded at all)
      // should _not_ be ignored
      pattern = this.include[i];

      if (this._matchesPattern(pattern, relativePath)) {
        return includeFileCache[relativePath] = true;
      }
    }

    // If no include patterns were matched, ignore this file.
    return includeFileCache[relativePath] = false;
  }

  // Otherwise, don't ignore this file
  return includeFileCache[relativePath] = true;
};

Funnel.prototype._matchesPattern = function(pattern, relativePath) {
  if (pattern instanceof RegExp) {
    return pattern.test(relativePath);
  } else if (pattern instanceof Minimatch) {
    return pattern.match(relativePath);
  } else if (typeof pattern === 'function') {
    return pattern(relativePath);
  }

  throw new Error('Pattern `' + pattern + '` was not a RegExp, Glob, or Function.');
};

Funnel.prototype.processFile = function(sourcePath, destPath /*, relativePath */) {
  this._copy(sourcePath, destPath);
};

Funnel.prototype._copy = function(sourcePath, destPath) {
  var destDir = path.dirname(destPath);

  try {
    symlinkOrCopy.sync(sourcePath, destPath);
  } catch(e) {
    if (!fs.existsSync(destDir)) {
      mkdirp.sync(destDir);
    }
    try {
      fs.unlinkSync(destPath);
    } catch(e) {

    }
    symlinkOrCopy.sync(sourcePath, destPath);
  }
};

module.exports = Funnel;
<commit_msg>fix failing tests<commit_after>'use strict';

var fs = require('fs');
var path = require('path-posix');
var mkdirp = require('mkdirp');
var walkSync = require('walk-sync');
var Minimatch = require('minimatch').Minimatch;
var arrayEqual = require('array-equal');
var Plugin = require('broccoli-plugin');
var symlinkOrCopy = require('symlink-or-copy');
var debug = require('debug');
var FSTree = require('fs-tree-diff');
var rimraf = require('rimraf');
var BlankObject = require('blank-object');
var heimdall = require('heimdalljs');

function ApplyPatchesSchema() {
  this.mkdir = 0;
  this.rmdir = 0;
  this.unlink = 0;
  this.change = 0;
  this.create = 0;
  this.other = 0;
  this.processed = 0;
  this.linked = 0;
}

function makeDictionary() {
  var cache = new BlankObject();

  cache['_dict'] = null;
  delete cache['_dict'];
  return cache;
}
// copied mostly from node-glob cc @isaacs
function isNotAPattern(pattern) {
  var set = new Minimatch(pattern).set;
  if (set.length > 1) {
    return false;
  }

  for (var j = 0; j < set[0].length; j++) {
    if (typeof set[0][j] !== 'string') {
      return false;
    }
  }

  return true;
}

Funnel.prototype = Object.create(Plugin.prototype);
Funnel.prototype.constructor = Funnel;
function Funnel(inputNode, options) {
  if (!(this instanceof Funnel)) { return new Funnel(inputNode, options); }

  Plugin.call(this, [inputNode], options);

  this._persistentOutput = true;

  this._includeFileCache = makeDictionary();
  this._destinationPathCache = makeDictionary();
  this._currentTree = new FSTree();
  this._lastInputPath = null;

  var keys = Object.keys(options || {});
  for (var i = 0, l = keys.length; i < l; i++) {
    var key = keys[i];
    this[key] = options[key];
  }

  this.destDir = this.destDir || '/';
  this.count = 0;

  if (this.files && typeof this.files === 'function') {
    // Save dynamic files func as a different variable and let the rest of the code
    // still assume that this.files is always an array.
    this._dynamicFilesFunc = this.files;
    delete this.files;
  } else if (this.files && !Array.isArray(this.files)) {
    throw new Error('Invalid files option, it must be an array or function (that returns an array).');
  }

  if ((this.files || this._dynamicFilesFunc) && (this.include || this.exclude)) {
    throw new Error('Cannot pass files option (array or function) and a include/exlude filter. You can only have one or the other');
  }

  if (this.files) {
    if (this.files.filter(isNotAPattern).length !== this.files.length) {
      console.warn('broccoli-funnel does not support `files:` option with globs, please use `include:` instead');
      this.include = this.files;
      this.files = undefined;
    }
  }

  this._setupFilter('include');
  this._setupFilter('exclude');

  this._matchedWalk = this.include && this.include.filter(function(a) {
    return a instanceof Minimatch;
  }).length === this.include.length;

  this._instantiatedStack = (new Error()).stack;
  this._buildStart = undefined;
}

Funnel.prototype._debugName = function() {
  return this.description || this._annotation || this.name || this.constructor.name;
};

Funnel.prototype._debug = function(message) {
  debug('broccoli-funnel:' + (this._debugName())).apply(null, arguments);
};

Funnel.prototype._setupFilter = function(type) {
  if (!this[type]) {
    return;
  }

  if (!Array.isArray(this[type])) {
    throw new Error('Invalid ' + type + ' option, it must be an array. You specified `' + typeof this[type] + '`.');
  }

  // Clone the filter array so we are not mutating an external variable
  var filters = this[type] = this[type].slice(0);

  for (var i = 0, l = filters.length; i < l; i++) {
    filters[i] = this._processPattern(filters[i]);
  }
};

Funnel.prototype._processPattern = function(pattern) {
  if (pattern instanceof RegExp) {
    return pattern;
  }

  var type = typeof pattern;

  if (type === 'string') {
    return new Minimatch(pattern);
  }

  if (type === 'function') {
    return pattern;
  }

  throw new Error('include/exclude patterns can be a RegExp, glob string, or function. You supplied `' + typeof pattern +'`.');
};

Funnel.prototype.shouldLinkRoots = function() {
  return !this.files && !this.include && !this.exclude && !this.getDestinationPath;
};

Funnel.prototype.build = function() {
  this._buildStart = new Date();
  this.destPath = path.join(this.outputPath, this.destDir);

  if (this.destPath[this.destPath.length -1] === '/') {
    this.destPath = this.destPath.slice(0, -1);
  }

  var inputPath = this.inputPaths[0];
  if (this.srcDir) {
    inputPath = path.join(inputPath, this.srcDir);
  }

  if (this._dynamicFilesFunc) {
    this.lastFiles = this.files;
    this.files = this._dynamicFilesFunc() || [];

    // Blow away the include cache if the list of files is new
    if (this.lastFiles !== undefined && !arrayEqual(this.lastFiles, this.files)) {
      this._includeFileCache = makeDictionary();
    }
  }

  var linkedRoots = false;
  if (this.shouldLinkRoots()) {
    linkedRoots = true;

    var inputPathExist = fs.existsSync(inputPath);

    if (this._lastInputPath ? !inputPathExist : inputPathExist) {
      rimraf.sync(this.outputPath);

      if (inputPathExist) {
        this._copy(inputPath, this.destPath);
      }
    }

    if (!inputPathExist && this.allowEmpty) {
      mkdirp.sync(this.destPath);
    }

    // TODO: verify if this scenario exists
    // Refer to test "can properly handle the output path being a broken symlink"
    if (inputPathExist && !fs.existsSync(this.outputPath)) {
      this._copy(inputPath, this.destPath);
    }

    this._lastInputPath = inputPath;
  } else {
    this.processFilters(inputPath);
  }

  this._debug('build, %o', {
    in: new Date() - this._buildStart + 'ms',
    linkedRoots: linkedRoots,
    inputPath: inputPath,
    destPath: this.destPath
  });
};

function ensureRelative(string) {
  if (string.charAt(0) === '/') {
    return string.substring(1);
  }
  return string;
}

Funnel.prototype._processEntries = function(entries) {
  return entries.filter(function(entry) {
    // support the second set of filters walk-sync does not support
    //   * regexp
    //   * excludes
    return this.includeFile(entry.relativePath);
  }, this).map(function(entry) {

    var relativePath = entry.relativePath;

    entry.relativePath = this.lookupDestinationPath(relativePath);

    this.outputToInputMappings[entry.relativePath] = relativePath;

    return entry;
  }, this);
};

Funnel.prototype._processPaths  = function(paths) {
  return paths.
    slice(0).
    filter(this.includeFile, this).
    map(function(relativePath) {
      var output = this.lookupDestinationPath(relativePath);
      this.outputToInputMappings[output] = relativePath;
      return output;
    }, this);
};

Funnel.prototype.processFilters = function(inputPath) {
  var nextTree;

  var instrumentation = heimdall.start('derivePatches');
  var entries;

  this.outputToInputMappings = {}; // we allow users to rename files

  if (this.files && !this.exclude && !this.include) {
    entries = this._processPaths(this.files);
    // clone to be compatible with walkSync
    nextTree = FSTree.fromPaths(entries, { sortAndExpand: true });
  } else {

    if (this._matchedWalk) {
      entries = walkSync.entries(inputPath, this.include);
    } else {
      entries = walkSync.entries(inputPath);
    }

    entries = this._processEntries(entries);
    nextTree = FSTree.fromEntries(entries, { sortAndExpand: true });
  }

  var patches = this._currentTree.calculatePatch(nextTree);

  this._currentTree = nextTree;

  instrumentation.stats.patches = patches.length;
  instrumentation.stats.entries = entries.length;

  var outputPath = this.outputPath;

  instrumentation.stop();

  instrumentation = heimdall.start('applyPatch', ApplyPatchesSchema);

  patches.forEach(function(entry) {
    this._applyPatch(entry, inputPath, outputPath, instrumentation.stats);
  }, this);

  instrumentation.stop();
};

Funnel.prototype._applyPatch = function applyPatch(entry, inputPath, _outputPath, stats) {
  var outputToInput = this.outputToInputMappings;
  var operation = entry[0];
  var outputRelative = entry[1];

  if (!outputRelative) {
    // broccoli itself maintains the roots, we can skip any operation on them
    return;
  }

  var outputPath = _outputPath + '/' + outputRelative;

  this._debug('%s %s', operation, outputPath);

  switch (operation) {
    case 'unlink' :
      stats.unlink++;

      fs.unlinkSync(outputPath);
      break;
    case 'rmdir'  :
      stats.rmdir++;
      fs.rmdirSync(outputPath);
      break;
    case 'mkdir'  :
      stats.mkdir++;
      fs.mkdirSync(outputPath);
      break;
    case 'change':
      stats.change++;
      /* falls through */
    case 'create':
      if (operation === 'create') {
        stats.create++;
      }

      var relativePath = outputToInput[outputRelative];
      if (relativePath === undefined) {
        relativePath = outputToInput['/' + outputRelative];
      }
      this.processFile(inputPath + '/' + relativePath, outputPath, relativePath);
      break;
    default: throw new Error('Unknown operation: ' + operation);
  }
};

Funnel.prototype.lookupDestinationPath = function(relativePath) {
  if (this._destinationPathCache[relativePath] !== undefined) {
    return this._destinationPathCache[relativePath];
  }

  // the destDir is absolute to prevent '..' above the output dir
  if (this.getDestinationPath) {
    return this._destinationPathCache[relativePath] = ensureRelative(path.join(this.destDir, this.getDestinationPath(relativePath)));
  }

  return this._destinationPathCache[relativePath] = ensureRelative(path.join(this.destDir, relativePath));
};

Funnel.prototype.includeFile = function(relativePath) {
  var includeFileCache = this._includeFileCache;

  if (includeFileCache[relativePath] !== undefined) {
    return includeFileCache[relativePath];
  }

  // do not include directories, only files
  if (relativePath[relativePath.length - 1] === '/') {
    return includeFileCache[relativePath] = false;
  }

  var i, l, pattern;

  // Check for specific files listing
  if (this.files) {
    return includeFileCache[relativePath] = this.files.indexOf(relativePath) > -1;
  }

  // Check exclude patterns
  if (this.exclude) {
    for (i = 0, l = this.exclude.length; i < l; i++) {
      // An exclude pattern that returns true should be ignored
      pattern = this.exclude[i];

      if (this._matchesPattern(pattern, relativePath)) {
        return includeFileCache[relativePath] = false;
      }
    }
  }

  // Check include patterns
  if (this.include && this.include.length > 0) {
    for (i = 0, l = this.include.length; i < l; i++) {
      // An include pattern that returns true (and wasn't excluded at all)
      // should _not_ be ignored
      pattern = this.include[i];

      if (this._matchesPattern(pattern, relativePath)) {
        return includeFileCache[relativePath] = true;
      }
    }

    // If no include patterns were matched, ignore this file.
    return includeFileCache[relativePath] = false;
  }

  // Otherwise, don't ignore this file
  return includeFileCache[relativePath] = true;
};

Funnel.prototype._matchesPattern = function(pattern, relativePath) {
  if (pattern instanceof RegExp) {
    return pattern.test(relativePath);
  } else if (pattern instanceof Minimatch) {
    return pattern.match(relativePath);
  } else if (typeof pattern === 'function') {
    return pattern(relativePath);
  }

  throw new Error('Pattern `' + pattern + '` was not a RegExp, Glob, or Function.');
};

Funnel.prototype.processFile = function(sourcePath, destPath /*, relativePath */) {
  this._copy(sourcePath, destPath);
};

Funnel.prototype._copy = function(sourcePath, destPath) {
  var destDir = path.dirname(destPath);

  try {
    symlinkOrCopy.sync(sourcePath, destPath);
  } catch(e) {
    if (!fs.existsSync(destDir)) {
      mkdirp.sync(destDir);
    }
    try {
      fs.unlinkSync(destPath);
    } catch(e) {

    }
    symlinkOrCopy.sync(sourcePath, destPath);
  }
};

module.exports = Funnel;
<|endoftext|>


<commit_before>
raptor.Calendar = function(id, config) {

	config = config || {};
	this.template = config.template;
	this.current_date = new raptor.Date();
	this.active_date = new raptor.Date(this.current_date);
}

raptor.Calendar.prototype = {

	_get_days : function() {

		var days = [], active_date = this.active_date;

		// format proper date combine
		var get_combine = function(i) { return active_date.year + active_date.month + (i < 10) ? '0' + i : i }
		console.log(get_combine(2))
		// current month props
		var curr_total = raptor.get_days_in_month(this.active_date.month, this.active_date.year);
		var curr_start = this.active_date.first_day_of_month().index;

		// previous month props
		var pre_month = new raptor.Date(this.active_date.year, this.active_date.month - 1, this.active_date.day);
		var pre_total = raptor.get_days_in_month(pre_month.month, pre_month.year);

		// build pre-days
		for (var i = pre_total - curr_start; i <= pre_total; i++) days.push({ date : i, out_of_range : true , date_combine : get_combine(i) });

		// build days
		for (i = 1; i <= curr_total; i++) days.push({ date : i, date_combine : get_combine(i) });

		// build post-days
		for (i = 1; days.length < 42; i++) days.push({ date : i, out_of_range : true, date_combine : get_combine(i) });

		return days;
	},

	build : function() {
		var days = this._get_days();
		if (this.template) return this.template(days, this);
		else return days;
	},

	step_back : function(steps) {
		this.active_date.step_back(steps);
	},

	step_forward : function(steps) {
		this.active_date.step_forward(steps);
	},

	set_date : function(date) {
		this.active_date = new raptor.Date(date);
	}
}<commit_msg>get_combine<commit_after>
raptor.Calendar = function(id, config) {

	config = config || {};
	this.template = config.template;
	this.current_date = new raptor.Date();
	this.active_date = new raptor.Date(this.current_date);
}

raptor.Calendar.prototype = {

	_get_days : function() {

		var days = [], active_date = this.active_date;

		// format proper date combine
		var get_combine = function(i) { return active_date.year + active_date.month + ((i < 10) ? '0' + i : i) }
		console.log(get_combine(2))
		// current month props
		var curr_total = raptor.get_days_in_month(this.active_date.month, this.active_date.year);
		var curr_start = this.active_date.first_day_of_month().index;

		// previous month props
		var pre_month = new raptor.Date(this.active_date.year, this.active_date.month - 1, this.active_date.day);
		var pre_total = raptor.get_days_in_month(pre_month.month, pre_month.year);

		// build pre-days
		for (var i = pre_total - curr_start; i <= pre_total; i++) days.push({ date : i, out_of_range : true , date_combine : get_combine(i) });

		// build days
		for (i = 1; i <= curr_total; i++) days.push({ date : i, date_combine : get_combine(i) });

		// build post-days
		for (i = 1; days.length < 42; i++) days.push({ date : i, out_of_range : true, date_combine : get_combine(i) });

		return days;
	},

	build : function() {
		var days = this._get_days();
		if (this.template) return this.template(days, this);
		else return days;
	},

	step_back : function(steps) {
		this.active_date.step_back(steps);
	},

	step_forward : function(steps) {
		this.active_date.step_forward(steps);
	},

	set_date : function(date) {
		this.active_date = new raptor.Date(date);
	}
}<|endoftext|>


<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';

foam.CLASS({
  package: 'org.chromium.webidl',
  name: 'ParserRunner',
  extends: 'org.chromium.webidl.PipelineRunner',

  requires: ['org.chromium.webidl.BaseParser'],

  documentation: 'Runnable Box that parsers IDLFileContents into ASTs.',

  methods: [
    function run(message) {
      if (this.validateMessage(message)) return;

      // Verify all required arguments are present.
      if (!message.idlFile || !message.parserClass)
        return this.error(this.fmtErrorMsg(this.MISSING_PROPS));

      var file = message.idlFile;
      var parserClass = message.parserClass;
      // Prepare metadata to be injected by parser.
      var metadata = Array.isArray(file.id) ? file.id.join('/') : file.id;

      // Load appropriate parser depending on configuration.
      // TODO: Replace injected string with a safer method, such as a
      // helper method that chooses parser based on URL.
      var parser = parserClass.create();
      foam.assert(this.BaseParser.isInstance(parser),
        'The class provided is not an instance of BaseParser.');

      var results = parser.parseString(file.contents, metadata);

      // Determine if parse of entire file was successful.
      if (!Array.isArray(results.value) ||
          file.contents.length !== results.pos) {
        var metadata = file.metadata || {};
        var id = `
          Repository: ${metadata.repository}
          Path: ${metadata.path}
          Revision: ${metadata.revision}`;

        this.error(new Error(`Incomplete parse on file. Metadata: ${id}`));
      } else {
        message.ast = results.value;
        this.output(message);
      }
    }
  ],
});
<commit_msg>Changing metadata for parse to class based instead of string.<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';

foam.CLASS({
  package: 'org.chromium.webidl',
  name: 'ParserRunner',
  extends: 'org.chromium.webidl.PipelineRunner',

  requires: ['org.chromium.webidl.BaseParser'],

  documentation: 'Runnable Box that parsers IDLFileContents into ASTs.',

  methods: [
    function run(message) {
      if (this.validateMessage(message)) return;

      // Verify all required arguments are present.
      if (!message.idlFile || !message.parserClass)
        return this.error(this.fmtErrorMsg(this.MISSING_PROPS));

      var file = message.idlFile;
      var parserClass = message.parserClass;
      // Prepare metadata to be injected by parser.
      var metadata = file.cls_.create({id: file.id});
      //    Array.isArray(file.id) ? file.id.join('/') : file.id;

      // Load appropriate parser depending on configuration.
      // TODO: Replace injected string with a safer method, such as a
      // helper method that chooses parser based on URL.
      var parser = parserClass.create();
      foam.assert(this.BaseParser.isInstance(parser),
        'The class provided is not an instance of BaseParser.');

      var results = parser.parseString(file.contents, metadata);

      // Determine if parse of entire file was successful.
      if (!Array.isArray(results.value) ||
          file.contents.length !== results.pos) {
        var metadata = file.metadata || {};
        var id = `
          Repository: ${metadata.repository}
          Path: ${metadata.path}
          Revision: ${metadata.revision}`;

        this.error(new Error(`Incomplete parse on file. Metadata: ${id}`));
      } else {
        message.ast = results.value;
        this.output(message);
      }
    }
  ],
});
<|endoftext|>


<commit_before>// @flow

const { logger } = require('@lagoon/commons/src/local-logging');
const { sendToLagoonLogs } = require('@lagoon/commons/src/logs');
const { createDeployTask } = require('@lagoon/commons/src/tasks');

import type { WebhookRequestData, removeData, ChannelWrapper, Project } from '../types';

async function bitbucketPullRequestUpdated(webhook: WebhookRequestData, project: Project) {

    const {
      webhooktype,
      event,
      giturl,
      uuid,
      body,
    } = webhook;

    console.log(body);

    const headBranchName = body.pullrequest.source.branch.name
    const headSha = body.pullrequest.source.commit.hash
    const baseBranchName = body.pullrequest.destination.branch.name
    const baseSha = body.pullrequest.destination.commit.hash

    const data: deployData = {
      pullrequestTitle: body.pullrequest.description,
      pullrequestNumber: body.pullrequest.id,
      projectName: project.name,
      type: 'pullrequest',
      headBranchName: headBranchName,
      headSha: headSha,
      baseBranchName: baseBranchName,
      baseSha: baseSha,
      branchName: `pr-${body.pullrequest.id}`,
    }

    try {
      const taskResult = await createDeployTask(data);
      sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:opened:handled`, data,
        `*[${project.name}]* PR <${body.pullrequest.destination.repository.links.html.href}|#${body.pullrequest.id} (${body.description})> updated in <${body.pullrequest.destination.repository.links.html.href}|${body.pullrequest.destination.branch.name}>`
      )
      return;
    } catch (error) {
      switch (error.name) {
        case "ProjectNotFound":
        case "NoActiveSystemsDefined":
        case "UnknownActiveSystem":
          // These are not real errors and also they will happen many times. We just log them locally but not throw an error
          sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:handledButNoTask`, meta,
            `*[${project.name}]* PR ${body.object_attributes.id} opened. No remove task created, reason: ${error}`
          )
          return;

        default:
          // Other messages are real errors and should reschedule the message in RabbitMQ in order to try again
          throw error
      }
    }
}

module.exports = bitbucketPullRequestUpdated;
<commit_msg>update description to title.<commit_after>// @flow

const { logger } = require('@lagoon/commons/src/local-logging');
const { sendToLagoonLogs } = require('@lagoon/commons/src/logs');
const { createDeployTask } = require('@lagoon/commons/src/tasks');

import type { WebhookRequestData, removeData, ChannelWrapper, Project } from '../types';

async function bitbucketPullRequestUpdated(webhook: WebhookRequestData, project: Project) {

    const {
      webhooktype,
      event,
      giturl,
      uuid,
      body,
    } = webhook;

    console.log(body);

    const headBranchName = body.pullrequest.source.branch.name
    const headSha = body.pullrequest.source.commit.hash
    const baseBranchName = body.pullrequest.destination.branch.name
    const baseSha = body.pullrequest.destination.commit.hash

    const data: deployData = {
      pullrequestTitle: body.pullrequest.title,
      pullrequestNumber: body.pullrequest.id,
      projectName: project.name,
      type: 'pullrequest',
      headBranchName: headBranchName,
      headSha: headSha,
      baseBranchName: baseBranchName,
      baseSha: baseSha,
      branchName: `pr-${body.pullrequest.id}`,
    }

    try {
      const taskResult = await createDeployTask(data);
      sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:opened:handled`, data,
        `*[${project.name}]* PR <${body.pullrequest.destination.repository.links.html.href}|#${body.pullrequest.id} (${body.title})> updated in <${body.pullrequest.destination.repository.links.html.href}|${body.pullrequest.destination.branch.name}>`
      )
      return;
    } catch (error) {
      switch (error.name) {
        case "ProjectNotFound":
        case "NoActiveSystemsDefined":
        case "UnknownActiveSystem":
          // These are not real errors and also they will happen many times. We just log them locally but not throw an error
          sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:handledButNoTask`, meta,
            `*[${project.name}]* PR ${body.object_attributes.id} opened. No remove task created, reason: ${error}`
          )
          return;

        default:
          // Other messages are real errors and should reschedule the message in RabbitMQ in order to try again
          throw error
      }
    }
}

module.exports = bitbucketPullRequestUpdated;
<|endoftext|>


<commit_before>const ParameterError = require('../errors/ParameterError');

class RegionAndPlatformUtil {

	static validatePlatformId(_platformId) {
		let isValid = false;
		if (_platformId && typeof _platformId === 'string') {
			isValid = RegionAndPlatformUtil.getPlatformIds().indexOf(_platformId.toLowerCase()) !== -1;
		}
		return isValid;
	}
	static validateRegion(_region) {
		let isValid = false;
		if (_region && typeof _region === 'string') {
			isValid = RegionAndPlatformUtil.getRegions().indexOf(_region.toLowerCase()) !== -1;
		}
		return isValid;
	}

	static getMappingRegionToPlatformId() {
		return {
			'br': 'br1',
			'eune': 'eun1',
			'euw': 'euw1',
			'jp': 'jp1',
			'kr': 'kr',
			'lan': 'la1',
			'las': 'la2',
			'na': 'na1',
			'oce': 'oc1',
			'tr': 'tr1',
			'ru': 'ru',
			'pbe': 'pbe1'
		};
	}
	static getPlatformIds() {
		const mapping = RegionAndPlatformUtil.getMappingRegionToPlatformId();
		return Object.keys(mapping).map(region => {
			return mapping[region];
		});
	}

	static getPlatformIdForRegion(region) {
		const mapping = RegionAndPlatformUtil.getMappingRegionToPlatformId();
		if (!region || typeof region !== 'string') {
			throw new ParameterError('region is missing');
		}
		const regionLower = region.toLowerCase();
		const platformId = mapping[regionLower];

		if (!platformId) {
			throw new Error(`No platformId available for given region "${region}"`);
		} else {
			return platformId;
		}
	}
	/**
	 * @throws Error if given argument is neither a valid platformId nor a valid region
	 * @param [platformIdOrRegion] case-insensitive. defaults to PLATFORM_ID set at instantiation of LeagueJs or from default-config.
	 * @return {string} platformId in lowercase
	 */
	static getPlatformIdFromPlatformIdOrRegion(platformIdOrRegion) {
		return RegionAndPlatformUtil.validatePlatformId(platformIdOrRegion) ? platformIdOrRegion.toLowerCase() : RegionAndPlatformUtil.getPlatformIdForRegion(platformIdOrRegion);
	}
	static getRegionForPlatformId(platformId) {
		const mapping = RegionAndPlatformUtil.getMappingRegionToPlatformId();
		if (!platformId || typeof platformId !== 'string') {
			throw new ParameterError('platformId is missing');
		}
		const platformIdLower = platformId.toLowerCase();
		const region = Object.keys(mapping).find(region => {
			return mapping[region] === platformIdLower;
		});

		if (!region) {
			throw new Error(`No region available for given platformId "${platformId}"`);
		} else {
			return region;
		}
	}
	static getRegions() {
		return Object.keys(RegionAndPlatformUtil.getMappingRegionToPlatformId());
	}
}
module.exports = RegionAndPlatformUtil;<commit_msg>chores (RegionAndPlatformUtil) remove PBE region PBE Spectator endpoint and with it support for PBE as endpoint region will be removed see https://discussion.developer.riotgames.com/articles/2626/pbe-deprecation-1.html<commit_after>const ParameterError = require('../errors/ParameterError');

class RegionAndPlatformUtil {

	static validatePlatformId(_platformId) {
		let isValid = false;
		if (_platformId && typeof _platformId === 'string') {
			isValid = RegionAndPlatformUtil.getPlatformIds().indexOf(_platformId.toLowerCase()) !== -1;
		}
		return isValid;
	}
	static validateRegion(_region) {
		let isValid = false;
		if (_region && typeof _region === 'string') {
			isValid = RegionAndPlatformUtil.getRegions().indexOf(_region.toLowerCase()) !== -1;
		}
		return isValid;
	}

	static getMappingRegionToPlatformId() {
		return {
			'br': 'br1',
			'eune': 'eun1',
			'euw': 'euw1',
			'jp': 'jp1',
			'kr': 'kr',
			'lan': 'la1',
			'las': 'la2',
			'na': 'na1',
			'oce': 'oc1',
			'tr': 'tr1',
			'ru': 'ru'
		};
	}
	static getPlatformIds() {
		const mapping = RegionAndPlatformUtil.getMappingRegionToPlatformId();
		return Object.keys(mapping).map(region => {
			return mapping[region];
		});
	}

	static getPlatformIdForRegion(region) {
		const mapping = RegionAndPlatformUtil.getMappingRegionToPlatformId();
		if (!region || typeof region !== 'string') {
			throw new ParameterError('region is missing');
		}
		const regionLower = region.toLowerCase();
		const platformId = mapping[regionLower];

		if (!platformId) {
			throw new Error(`No platformId available for given region "${region}"`);
		} else {
			return platformId;
		}
	}
	/**
	 * @throws Error if given argument is neither a valid platformId nor a valid region
	 * @param [platformIdOrRegion] case-insensitive. defaults to PLATFORM_ID set at instantiation of LeagueJs or from default-config.
	 * @return {string} platformId in lowercase
	 */
	static getPlatformIdFromPlatformIdOrRegion(platformIdOrRegion) {
		return RegionAndPlatformUtil.validatePlatformId(platformIdOrRegion) ? platformIdOrRegion.toLowerCase() : RegionAndPlatformUtil.getPlatformIdForRegion(platformIdOrRegion);
	}
	static getRegionForPlatformId(platformId) {
		const mapping = RegionAndPlatformUtil.getMappingRegionToPlatformId();
		if (!platformId || typeof platformId !== 'string') {
			throw new ParameterError('platformId is missing');
		}
		const platformIdLower = platformId.toLowerCase();
		const region = Object.keys(mapping).find(region => {
			return mapping[region] === platformIdLower;
		});

		if (!region) {
			throw new Error(`No region available for given platformId "${platformId}"`);
		} else {
			return region;
		}
	}
	static getRegions() {
		return Object.keys(RegionAndPlatformUtil.getMappingRegionToPlatformId());
	}
}
module.exports = RegionAndPlatformUtil;<|endoftext|>


<commit_before>module.exports = {
  build: [
    `rimraf dist/`,
    `tsc -p src`
  ],
  lint: {
    ts: `tslint "src/**/*.ts"`,
    js: `standard "**/*.config.js"`
  },
  test: [
    'tsc -p spec',
    'jasmine'
  ],
  fix: `standard --fix "**/*.config.js"`,
  release: `clean-release`
}
<commit_msg>add tslint fix script<commit_after>module.exports = {
  build: [
    `rimraf dist/`,
    `tsc -p src`
  ],
  lint: {
    ts: `tslint "src/**/*.ts"`,
    js: `standard "**/*.config.js"`
  },
  test: [
    'tsc -p spec',
    'jasmine'
  ],
  fix: {
    ts: `tslint --fix "src/**/*.ts"`,
    js: `standard --fix "**/*.config.js"`
  },
  release: `clean-release`
}
<|endoftext|>


<commit_before>var Transform = require('pipestream').Transform;
var util = require('util');
var config = require('../config');
var STATUS_CODES = require('http').STATUS_CODES || {};

function FileWriterTransform(writer, source, isRaw, req, isReq) {
  if (!(this instanceof FileWriterTransform)) {
    return new FileWriterTransform(writer, source, isRaw, req, isReq);
  }
  var self = this;
  Transform.call(self);
  self._writer = writer;
  source.on('error', function() {
    writer.end();
  });
  isRaw && writer.write(getRawData(source, req, isReq));
}

function getRawData(source, req, isReq) {
  var firstLine;
  if (req) {
    var message = source.statusMessage || STATUS_CODES[source.statusCode] || '';
    firstLine = ['HTTP/' + (req.httpVersion || '1.1'), source.statusCode, message].join(' ');
  } else {
    firstLine = [source.method, source.url, 'HTTP/' + (source.httpVersion || '1.1')].join(' ');
  }

  var headers = [];
  var rawHeaderNames = source.rawHeaderNames || {};
  Object.keys(source.headers).forEach(function(key) {
    var val = source.headers[key];
    if (!isReq || (key !== config.HTTPS_FIELD && key !== config.CLIENT_IP_HEAD && key !== 'content-encoding')) {
      key = rawHeaderNames[key] || key;
      headers.push(Array.isArray(val) ? val.map(function(item) {
        return key + ': ' + item;
      }).join('\r\n') : key + ': ' + val);
    }
  });

  return firstLine + '\r\n' + headers.join('\r\n') + '\r\n\r\n';
}

util.inherits(FileWriterTransform, Transform);

FileWriterTransform.prototype._transform = function(chunk, encoding, callback) {
  if (chunk) {
    this._writer.write(chunk);
  } else {
    this._writer.end();
  }

  callback(null, chunk);
};

module.exports = FileWriterTransform;
<commit_msg>feat: Add x-forwarded-for header<commit_after>var Transform = require('pipestream').Transform;
var util = require('util');
var config = require('../config');
var STATUS_CODES = require('http').STATUS_CODES || {};

function FileWriterTransform(writer, source, isRaw, req, isReq) {
  if (!(this instanceof FileWriterTransform)) {
    return new FileWriterTransform(writer, source, isRaw, req, isReq);
  }
  var self = this;
  Transform.call(self);
  self._writer = writer;
  source.on('error', function() {
    writer.end();
  });
  isRaw && writer.write(getRawData(source, req, isReq));
}

function getRawData(source, req, isReq) {
  var firstLine;
  if (req) {
    var message = source.statusMessage || STATUS_CODES[source.statusCode] || '';
    firstLine = ['HTTP/' + (req.httpVersion || '1.1'), source.statusCode, message].join(' ');
  } else {
    firstLine = [source.method, source.url, 'HTTP/' + (source.httpVersion || '1.1')].join(' ');
  }

  var headers = [];
  var rawHeaderNames = source.rawHeaderNames || {};
  Object.keys(source.headers).forEach(function(key) {
    var val = source.headers[key];
    if (!isReq || (key !== config.HTTPS_FIELD && key !== 'content-encoding')) {
      key = rawHeaderNames[key] || key;
      headers.push(Array.isArray(val) ? val.map(function(item) {
        return key + ': ' + item;
      }).join('\r\n') : key + ': ' + val);
    }
  });

  return firstLine + '\r\n' + headers.join('\r\n') + '\r\n\r\n';
}

util.inherits(FileWriterTransform, Transform);

FileWriterTransform.prototype._transform = function(chunk, encoding, callback) {
  if (chunk) {
    this._writer.write(chunk);
  } else {
    this._writer.end();
  }

  callback(null, chunk);
};

module.exports = FileWriterTransform;
<|endoftext|>


<commit_before>#!/bin/env node
//and the fun begins here :3

var App =  function(){
	this.fs = require('fs'); //File System
	this.path = require('path'); //For handling and transforming file paths.
	this.http = require('http').createServer(handle); //HTTP server 'handler' function that runs
	this.io = require('socket.io'); //Websockets/socket.io
	this.mongo = require('mongodb').MongoClient; //MongoDB client
	this.express = require('express'); //require express :p I kinda dislike it but openshift pleases me to do it I think! :(
	/*********************************************************************
	***************************Help Functions!****************************
	*********************************************************************/

	//setup Ip and Port env vars
	this.setupVariables = function(){
		this.ipAddress = process.env.OPENSHIFT_NODEJS_IP; //IP ADDRESS
		this.port = process.env.OPENSHIFT_NODEJS_PORT || 8080; //PORT internal or 8080

		//If the IP is not available then set it to local '127.0.0.1'
		if(typeof this.ipAddress === "undefined"){
			//
			console.warn("No OPENSHIFT_NODEJS_IP var, using 127.0.0.1");
			this.ipAddress = "127.0.0.1";
		}
	};

	//populate cache
	this.populateCache = function(){
		if(typeof this.zCache === "undefined"){ //if zCache s undefined
			this.zCache = { 'index.html': '' };
		}
		this.zCache['index.html'] = fs.readFileSync('./public/index.html');
		console.log("Dat Html! Yummy :D");
	};
	//*****************************************************************

	/******************************************************************
	*Retrieve Entry Content For Cache
	*******************************************************************/

	this.getCache = function(key){
		return this.zCache[key];
	};

	/*
		*Terminator - THe termination handler.
		*Terminate server on receipt of the specified signal.
		*@param {string} signal  Signal to terminate on.
	*/
	this.terminator = function(signal){
		if(typeof signal === "string"){
			console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), signal);
		}
		console.log('%s: Node server stopped.', Date(Date.now()) );
		//indicate that node server is stopped!
		process.exit(1);
	};

	/*****************************************************************
     *  Setup termination handlers (for exit and a list of signals).
     *****************************************************************/

    this.setupTerminationHandlers = function(){
     	//  Process on exit and signals.
     	process.on('exit', function(){
     		this.terminator();
     	});
     	//bugz
     	['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { this.terminator(element); });
        });
    };
    //termination process is done!

    /*********************************************************************
    *************************Main Server Logic****************************
    *********************************************************************/

    /*
    	*Routing entries
    */
    this.createRoutes = function(){
    	this.routes = {};
    	//routes handler for main folder
    	this.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(this.getCache('index.html') );
        };
    };

    /*
    	*Initialize Serv
    */
    this.initializeServer = function(){
    	//get routes
    	this.createRoutes();
    	//create express server
    	this.serv = this.express.createServer();
    	//add handlers for routes
    	for (var r in this.routes) {
            this.serv.get(r, this.routes[r]);
        }
    };

    /*
    	*Initialize the application
    */

    this.initialize = function(){
    	//Setup Main Vars
    	this.setupVariables();
    	//Populate Cache
    	this.populateCache();
    	//Setup Termination Handlers
    	this.setupTerminationHandlers();

    	//create express server and routes
    	this.initializeServer();
    };

    /*
    	*Start The Server!
    */

    this.start = function(){
    	//Start the app on the port and ip
    	this.serv.listen(this.port,this.ipAddress,function(){
    		console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), this.ipaddress, this.port);
    	});
    }
}

/*************************************************************************/
/***************************App Config is done****************************/
/*************************************************************************/

//Create new app using of App class
var app = new App();
app.initialize();
app.start();

<commit_msg>Wheew! Handlers From Past Called me! :D<commit_after>#!/bin/env node
//and the fun begins here :3

var App =  function(){
	this.fs = require('fs'); //File System
	this.path = require('path'); //For handling and transforming file paths.
	this.http = require('http'); //HTTP server 'handler' function that runs
	this.io = require('socket.io'); //Websockets/socket.io
	this.mongo = require('mongodb').MongoClient; //MongoDB client
	this.express = require('express'); //require express :p I kinda dislike it but openshift pleases me to do it I think! :(
	/*********************************************************************
	***************************Help Functions!****************************
	*********************************************************************/

	//setup Ip and Port env vars
	this.setupVariables = function(){
		this.ipAddress = process.env.OPENSHIFT_NODEJS_IP; //IP ADDRESS
		this.port = process.env.OPENSHIFT_NODEJS_PORT || 8080; //PORT internal or 8080

		//If the IP is not available then set it to local '127.0.0.1'
		if(typeof this.ipAddress === "undefined"){
			//
			console.warn("No OPENSHIFT_NODEJS_IP var, using 127.0.0.1");
			this.ipAddress = "127.0.0.1";
		}
	};

	//populate cache
	this.populateCache = function(){
		if(typeof this.zCache === "undefined"){ //if zCache s undefined
			this.zCache = { 'index.html': '' };
		}
		this.zCache['index.html'] = fs.readFileSync('./public/index.html');
		console.log("Dat Html! Yummy :D");
	};
	//*****************************************************************

	/******************************************************************
	*Retrieve Entry Content For Cache
	*******************************************************************/

	this.getCache = function(key){
		return this.zCache[key];
	};

	/*
		*Terminator - THe termination handler.
		*Terminate server on receipt of the specified signal.
		*@param {string} signal  Signal to terminate on.
	*/
	this.terminator = function(signal){
		if(typeof signal === "string"){
			console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), signal);
		}
		console.log('%s: Node server stopped.', Date(Date.now()) );
		//indicate that node server is stopped!
		process.exit(1);
	};

	/*****************************************************************
     *  Setup termination handlers (for exit and a list of signals).
     *****************************************************************/

    this.setupTerminationHandlers = function(){
     	//  Process on exit and signals.
     	process.on('exit', function(){
     		this.terminator();
     	});
     	//bugz
     	['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { this.terminator(element); });
        });
    };
    //termination process is done!

    /*********************************************************************
    *************************Main Server Logic****************************
    *********************************************************************/

    /*
    	*Routing entries
    */
    this.createRoutes = function(){
    	this.routes = {};
    	//routes handler for main folder
    	this.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(this.getCache('index.html') );
        };
    };

    /*
    	*Initialize Serv
    */
    this.initializeServer = function(){
    	//get routes
    	this.createRoutes();
    	//create express server
    	this.serv = this.express.createServer();
    	//add handlers for routes
    	for (var r in this.routes) {
            this.serv.get(r, this.routes[r]);
        }
    };

    /*
    	*Initialize the application
    */

    this.initialize = function(){
    	//Setup Main Vars
    	this.setupVariables();
    	//Populate Cache
    	this.populateCache();
    	//Setup Termination Handlers
    	this.setupTerminationHandlers();

    	//create express server and routes
    	this.initializeServer();
    };

    /*
    	*Start The Server!
    */

    this.start = function(){
    	//Start the app on the port and ip
    	this.serv.listen(this.port,this.ipAddress,function(){
    		console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), this.ipaddress, this.port);
    	});
    }
}

/*************************************************************************/
/***************************App Config is done****************************/
/*************************************************************************/

//Create new app using of App class
var app = new App();
app.initialize();
app.start();

<|endoftext|>


<commit_before>//Karyoviewer object
jviz.modules.karyoviewer = function(opt)
{
  //Check the options
  if(typeof opt !== 'object'){ var opt = {}; }

  //Save the ideogram ID
  this._id = (typeof opt.id === 'undefined') ? jviz.misc.getID({ prefix: 'karyoviewer', length: 5 }) : opt.id;

  //Save the ideogram class
  this._class = (typeof opt.class === 'undefined') ? 'jviz-modules-karyoviewer' : opt.class;

  //Parent element
  this._parent = opt.parent;

  //Default size
  this._width = 0; //Default width
  this._height = 0; //Default height

  //Margins
  //this._margin = { top: 30, bottom: 30, left: 40, right: 40 };

  //Orientation
  this._orientation = {};
  this._orientation.actual = ''; //Actual orientation name
  this._orientation.default = 'portrait'; //Default orientation
  this._orientation.values = [ 'portrait', 'landscape' ]; //Orientation values

  //Block configuration
  this._block = {};
  this._block.width = 0; //Block width
  this._block.height = 0; //Block height
  this._block.draw = { width: 0, height: 0 }; //Block draw zone
  this._block.margin = { top: 30, bottom: 30, left: 0, right: 0 }; //Block margins
  this._block.resized = false; //Block is resized

  //Block default values
  this._block.default = {};

  //Default values for protrait
  this._block.default.portrait = {};
  this._block.default.portrait.draw_width = 15; //Default portrait draw width
  this._block.default.portrait.draw_height = 70; //Default portrait draw height
  this._block.default.portrait.margin_top = 30; //Default portrait margin top
  this._block.default.portrait.margin_bottom = 30; //Default portrait margin bottom

  //Default values for landscape
  this._block.default.landscape = {};
  this._block.default.landscape.draw_width = 0; //Default landscape draw width
  this._block.default.landscape.draw_height = 20; //Default landscape draw height
  this._block.default.landscape.margin_top = 30; //Default landscape margin top
  this._block.default.landscape.margin_bottom = 30; //Default landscape margin bottom
  this._block.default.landscape.margin_left = 50; //Default landscape margin left
  this._block.default.landscape.margin_right = 50; //Default landscape margin right

  //Panel object
  this._panel = {};
  this._panel.el = null; //Panel element
  this._panel.id = this._id + '-panel'; //Panel id
  this._panel.parent = this._id; //Panel parent
  this._panel.title = (typeof opt.title === 'string') ? opt.title : 'Karyotype viewer'; //Panel title
  this._panel.detail = (typeof opt.detail === 'string') ? opt.detail : ''; //Panel detail
  this._panel.detail = ''; //Panel detail
  this._panel.visible = (typeof opt.panel === 'boolean') ? opt.panel : true; //Panel is visible
  this._panel.foot = false; //Disable foot

  //Canvas object
  this._canvas = {};
  this._canvas.id = this._id + '-canvas'; //Canvas ID
  this._canvas.parent = this._id; //Parent canvas ID
  this._canvas.width = '100%'; //Canvas width
  this._canvas.height = 0; //Canvas height
  this._canvas.layers = 3; //Number of layers
  this._canvas.el = null; //Canvas element

  //Check the chromosomes object
  if(typeof opt.chromosomes !== 'object'){ opt.chromosomes = {}; }

  //Chromosomes info
  this._chromosomes = {};
  this._chromosomes.width = 15; //Chromosome default width
  this._chromosomes.height = 20; //Chromosome default height
  this._chromosomes.layer = 1; //Chromosome layer
  this._chromosomes.list = []; //Chromosomes list
  this._chromosomes.index = {}; //Chromosomes index
  this._chromosomes.names = {}; //Chromosome names
  this._chromosomes.max = 0; //Chromosome max length
  this._chromosomes.num = 0; //Number of chromosomes
  this._chromosomes.color = jviz.colors.blue2.hex; //Chromosome color
  this._chromosomes.opacity = 0.6; //Chromosome opacity
  this._chromosomes.resized = false; //Chromosome data is resized

  //Chromosome radius
  this._chromosomes.radius = {};
  this._chromosomes.radius.portrait = 6; //Chromosome radius for portrait
  this._chromosomes.radius.landscape = 10; //Chromosome radius for landscape

  //Chromosome name
  this._chromosomes.name = {};
  this._chromosomes.name.list = []; //List of chromosomes names
  this._chromosomes.name.visible = true; //Chromosome name is visible
  this._chromosomes.name.margin = 7; //Chromosome name margin

  //Chromosome name text
  this._chromosomes.name.text = {};
  this._chromosomes.name.text.font = jviz.font.default; //Chromosome name text font
  this._chromosomes.name.text.size = '12px'; //Chromosome name text size
  this._chromosomes.name.text.align = 'center'; //Chromosome name text align

  //Centromere
  this._chromosomes.centromere = {};
  this._chromosomes.centromere.list = []; //List of centromere positions
  this._chromosomes.centromere.opacity = 0.9; //Centromere opacity

  //Check the features object
  if(typeof opt.features === 'undefined'){ opt.features = {}; }

  //Features object
  this._features = {};
  this._features.list = []; //List of features
  this._features.chromosomes = {}; //List of features by chromosomes
  this._features.layer = 2; //Features layer
  this._features.color = (typeof opt.features.color === 'string') ? opt.features.color : jviz.colors.red.hex; //Features default color
  this._features.opacity = 0.8; //Features opacity
  this._features.resized = false; //Features data is resized

  //Features counter
  this._features.counter = {};
  this._features.counter.list = {}; //Features counter
  this._features.counter.opacity = 1.0; //Features counter opacity
  this._features.counter.visible = (typeof opt.features.count === 'boolean') ? opt.features.count : true; //Features counter is visible
  this._features.counter.margin = 3; //Counter margin

  //Features counter rectangle
  this._features.counter.rectangle = {};
  this._features.counter.rectangle.width = 30; //Counter rectangle width
  this._features.counter.rectangle.height = 22; //Counter rectangle height
  this._features.counter.rectangle.radius = 5; //Counter rectangle radius

  //Features counter text
  this._features.counter.text = {};
  this._features.counter.text.font = jviz.font.default; //Counter font family
  this._features.counter.text.size = '12px'; //Counter text size
  this._features.counter.text.align = 'center'; //Counter text align
  this._features.counter.text.color = jviz.colors.white.hex; //Counter text color
  this._features.counter.text.margin = 7; //Counter text margin

  //Features counter triangle
  this._features.counter.triangle = {};
  this._features.counter.triangle.width = 6; //Features counter triangle width
  this._features.counter.triangle.height = 4; //Features counter triangle height

  //Features label
  this._features.label = {};
  this._features.label.opacity = 1.0; //Features label opacity
  this._features.label.visible = (typeof opt.features.label === 'boolean') ? opt.features.label : true; //Label visible

  //Features label rectangle
  this._features.label.rectangle = {};
  this._features.label.rectangle.width = 0; //Features label rectangle width
  this._features.label.rectangle.height = 0; //Features label rectangle height
  this._features.label.rectangle.radius = 5; //Features label rectangle radius

  //Chromosomes hover
  this._hover = {};
  this._hover.index = -1; //Hover chromosome index
  this._hover.margin = { top: 10, bottom: 20, left: 10, right: 10 }; //Hover margin
  this._hover.color = jviz.colors.white.hex; //Hover background color
  this._hover.opacity = 1.0; //Hover background color opacity
  this._hover.radius = 10; //Hover radius
  this._hover.layer = 0; //Hover layer

  //Check for undefined orientation
  if(typeof opt.orientation !== 'string'){ opt.orientation = 'portrait'; }

  //Build the karyotype element
  this.build();

  //Register the events
  this.events();

  //Parse the orientation
  this.orientation(opt.orientation);

  //Return this
  return this;
};
<commit_msg>js/karyoviewer.js: remove features counter definitions -> use the canvas-tooltip method of jviz<commit_after>//Karyoviewer object
jviz.modules.karyoviewer = function(opt)
{
  //Check the options
  if(typeof opt !== 'object'){ var opt = {}; }

  //Save the ideogram ID
  this._id = (typeof opt.id === 'undefined') ? jviz.misc.getID({ prefix: 'karyoviewer', length: 5 }) : opt.id;

  //Save the ideogram class
  this._class = (typeof opt.class === 'undefined') ? 'jviz-modules-karyoviewer' : opt.class;

  //Parent element
  this._parent = opt.parent;

  //Default size
  this._width = 0; //Default width
  this._height = 0; //Default height

  //Margins
  //this._margin = { top: 30, bottom: 30, left: 40, right: 40 };

  //Orientation
  this._orientation = {};
  this._orientation.actual = ''; //Actual orientation name
  this._orientation.default = 'portrait'; //Default orientation
  this._orientation.values = [ 'portrait', 'landscape' ]; //Orientation values

  //Block configuration
  this._block = {};
  this._block.width = 0; //Block width
  this._block.height = 0; //Block height
  this._block.draw = { width: 0, height: 0 }; //Block draw zone
  this._block.margin = { top: 30, bottom: 30, left: 0, right: 0 }; //Block margins
  this._block.resized = false; //Block is resized

  //Block default values
  this._block.default = {};

  //Default values for protrait
  this._block.default.portrait = {};
  this._block.default.portrait.draw_width = 15; //Default portrait draw width
  this._block.default.portrait.draw_height = 70; //Default portrait draw height
  this._block.default.portrait.margin_top = 30; //Default portrait margin top
  this._block.default.portrait.margin_bottom = 30; //Default portrait margin bottom

  //Default values for landscape
  this._block.default.landscape = {};
  this._block.default.landscape.draw_width = 0; //Default landscape draw width
  this._block.default.landscape.draw_height = 20; //Default landscape draw height
  this._block.default.landscape.margin_top = 30; //Default landscape margin top
  this._block.default.landscape.margin_bottom = 30; //Default landscape margin bottom
  this._block.default.landscape.margin_left = 50; //Default landscape margin left
  this._block.default.landscape.margin_right = 50; //Default landscape margin right

  //Panel object
  this._panel = {};
  this._panel.el = null; //Panel element
  this._panel.id = this._id + '-panel'; //Panel id
  this._panel.parent = this._id; //Panel parent
  this._panel.title = (typeof opt.title === 'string') ? opt.title : 'Karyotype viewer'; //Panel title
  this._panel.detail = (typeof opt.detail === 'string') ? opt.detail : ''; //Panel detail
  this._panel.detail = ''; //Panel detail
  this._panel.visible = (typeof opt.panel === 'boolean') ? opt.panel : true; //Panel is visible
  this._panel.foot = false; //Disable foot

  //Canvas object
  this._canvas = {};
  this._canvas.id = this._id + '-canvas'; //Canvas ID
  this._canvas.parent = this._id; //Parent canvas ID
  this._canvas.width = '100%'; //Canvas width
  this._canvas.height = 0; //Canvas height
  this._canvas.layers = 3; //Number of layers
  this._canvas.el = null; //Canvas element

  //Check the chromosomes object
  if(typeof opt.chromosomes !== 'object'){ opt.chromosomes = {}; }

  //Chromosomes info
  this._chromosomes = {};
  this._chromosomes.width = 15; //Chromosome default width
  this._chromosomes.height = 20; //Chromosome default height
  this._chromosomes.layer = 1; //Chromosome layer
  this._chromosomes.list = []; //Chromosomes list
  this._chromosomes.index = {}; //Chromosomes index
  this._chromosomes.names = {}; //Chromosome names
  this._chromosomes.max = 0; //Chromosome max length
  this._chromosomes.num = 0; //Number of chromosomes
  this._chromosomes.color = jviz.colors.blue2.hex; //Chromosome color
  this._chromosomes.opacity = 0.6; //Chromosome opacity
  this._chromosomes.resized = false; //Chromosome data is resized

  //Chromosome radius
  this._chromosomes.radius = {};
  this._chromosomes.radius.portrait = 6; //Chromosome radius for portrait
  this._chromosomes.radius.landscape = 10; //Chromosome radius for landscape

  //Chromosome name
  this._chromosomes.name = {};
  this._chromosomes.name.list = []; //List of chromosomes names
  this._chromosomes.name.visible = true; //Chromosome name is visible
  this._chromosomes.name.margin = 7; //Chromosome name margin

  //Chromosome name text
  this._chromosomes.name.text = {};
  this._chromosomes.name.text.font = jviz.font.default; //Chromosome name text font
  this._chromosomes.name.text.size = '12px'; //Chromosome name text size
  this._chromosomes.name.text.align = 'center'; //Chromosome name text align

  //Centromere
  this._chromosomes.centromere = {};
  this._chromosomes.centromere.list = []; //List of centromere positions
  this._chromosomes.centromere.opacity = 0.9; //Centromere opacity

  //Check the features object
  if(typeof opt.features === 'undefined'){ opt.features = {}; }

  //Features object
  this._features = {};
  this._features.list = []; //List of features
  this._features.chromosomes = {}; //List of features by chromosomes
  this._features.layer = 2; //Features layer
  this._features.color = (typeof opt.features.color === 'string') ? opt.features.color : jviz.colors.red.hex; //Features default color
  this._features.opacity = 0.8; //Features opacity
  this._features.resized = false; //Features data is resized

  //Features counter
  this._features.counter = {};
  this._features.counter.list = {}; //Features counter
  this._features.counter.opacity = 1.0; //Features counter opacity
  this._features.counter.visible = (typeof opt.features.count === 'boolean') ? opt.features.count : true; //Features counter is visible
  this._features.counter.margin = 3; //Counter margin

  //Features label
  this._features.label = {};
  this._features.label.opacity = 1.0; //Features label opacity
  this._features.label.visible = (typeof opt.features.label === 'boolean') ? opt.features.label : true; //Label visible

  //Features label rectangle
  this._features.label.rectangle = {};
  this._features.label.rectangle.width = 0; //Features label rectangle width
  this._features.label.rectangle.height = 0; //Features label rectangle height
  this._features.label.rectangle.radius = 5; //Features label rectangle radius

  //Chromosomes hover
  this._hover = {};
  this._hover.index = -1; //Hover chromosome index
  this._hover.margin = { top: 10, bottom: 20, left: 10, right: 10 }; //Hover margin
  this._hover.color = jviz.colors.white.hex; //Hover background color
  this._hover.opacity = 1.0; //Hover background color opacity
  this._hover.radius = 10; //Hover radius
  this._hover.layer = 0; //Hover layer

  //Check for undefined orientation
  if(typeof opt.orientation !== 'string'){ opt.orientation = 'portrait'; }

  //Build the karyotype element
  this.build();

  //Register the events
  this.events();

  //Parse the orientation
  this.orientation(opt.orientation);

  //Return this
  return this;
};
<|endoftext|>


<commit_before>var SensorTag = require('sensortag');
var mqtt = require('mqtt');

var client  = mqtt.connect('mqtt://');
var deviceID = [
    {"uuid":"b0b448c04303", "ovassid":"12015112820", "secret":"************"},
    {"uuid":"b0b448bc4d00", "ovassid":"12015112818", "secret":"************"},
    {"uuid":"b0b448c04305", "ovassid":"12015112865", "secret":"************"},
    {"uuid":"b0b448c08c02", "ovassid":"12015112892", "secret":"************"},
    {"uuid":"b0b448bcd003", "ovassid":"12015112885", "secret":"************"},
];

client.on('connect', function(){
    for (i in deviceID){
        client.subscribe('devices/' + deviceID[i].ovassid + '/down');
    }
});

client.on('message', function(topic, message){
    console.log(message.toString());
});

function publish(device, data){
    for (i in deviceID){
        if (deviceID[i].uuid = device.uuid){
            client.publish('devices/' + deviceID[i].ovassid + '/up', data);
        }
    }
}

function onDiscover(device) {
    console.log('Discovered device with UUID: ' + device['uuid']);

    device.connect(function(){
        connected = true;
        console.log('Connected To Sensor Tag');
        device.discoverServicesAndCharacteristics(function(callback){
            initAirSensors();
            initAccelAndGyro();
        });
    });

    device.on('disconnect', function(onDisconnect) {
        connected = false;
        client.end();
        console.log('Device disconnected.');
    });

    function initAccelAndGyro() {
        device.enableAccelerometer();
        device.notifyAccelerometer(function(){});
        device.enableGyroscope();
        device.notifyGyroscope(function(){});
        device.enableMagnetometer();
        device.notifyMagnetometer(function(){});
    };

    device.on('gyroscopeChange', function(x, y, z) {
        var data = {
            "sensor": "gyroscope",
            "gyroX" : x,
            "gyroY" : y,
            "gyroZ" : z
        };
        publish(device, data);
    });

    device.on('accelerometerChange', function(x, y, z) {
        var data = {
            "sensor": "accelerometer",
            "accelX" : x,
            "accelY" : y,
            "accelZ" : z
        };
        publish(device, data);
    });

    device.on('magnetometerChange', function(x, y, z) {
        var data = {
            "sensor": "magnetometer",
            "magX" : x,
            "magY" : y,
            "magZ" : z
        };
        publish(device, data);
    });

    function initAirSensors() {
        device.enableIrTemperature();
        device.enableHumidity();
        device.enableBarometricPressure();
        var intervalId = setInterval(function() {
            if(!connected) {
                clearInterval(intervalId);
                return;
            }
            device.readBarometricPressure(function(pressure) {
                device.readHumidity(function(temperature, humidity) {
                    device.readIrTemperature(function(objectTemperature, ambientTemperature) {
                        var data = {
                            "sensor": "air",
                            "pressure" : pressure,
                            "humidity" : humidity,
                            "objTemp" : objectTemperature,
                            "ambientTemp" : ambientTemperature,
                            "temp" : temperature
                        };
                        publish(device, data);
                    });
                });
            });
        }, 5000);
    }
}

console.log('Make sure the Sensor Tag is on!');

SensorTag.discoverAll(onDiscover);<commit_msg>Fixed variable format issue<commit_after>var SensorTag = require('sensortag');
var mqtt = require('mqtt');

var client  = mqtt.connect('mqtt://');
var deviceID = [
    {"uuid":"b0b448c04303", "ovassid":"12015112820", "secret":"************"},
    {"uuid":"b0b448bc4d00", "ovassid":"12015112818", "secret":"************"},
    {"uuid":"b0b448c04305", "ovassid":"12015112865", "secret":"************"},
    {"uuid":"b0b448c08c02", "ovassid":"12015112892", "secret":"************"},
    {"uuid":"b0b448bcd003", "ovassid":"12015112885", "secret":"************"},
];

client.on('connect', function(){
    for (i in deviceID){
        client.subscribe('devices/' + deviceID[i].ovassid + '/down');
    }
});

client.on('message', function(topic, message){
    console.log(message.toString());
});

function publish(device, data){
    for (i in deviceID){
        if (deviceID[i].uuid = device.uuid){
            client.publish('devices/' + deviceID[i].ovassid + '/up', JSON.stringify(data));
        }
    }
}

function onDiscover(device) {
    console.log('Discovered device with UUID: ' + device['uuid']);

    device.connect(function(){
        connected = true;
        console.log('Connected To Sensor Tag');
        device.discoverServicesAndCharacteristics(function(callback){
            initAirSensors();
            initAccelAndGyro();
        });
    });

    device.on('disconnect', function(onDisconnect) {
        connected = false;
        client.end();
        console.log('Device disconnected.');
    });

    function initAccelAndGyro() {
        device.enableAccelerometer();
        device.notifyAccelerometer(function(){});
        device.enableGyroscope();
        device.notifyGyroscope(function(){});
        device.enableMagnetometer();
        device.notifyMagnetometer(function(){});
    };

    device.on('gyroscopeChange', function(x, y, z) {
        var data = {
            "sensor": "gyroscope",
            "gyroX" : x,
            "gyroY" : y,
            "gyroZ" : z
        };
        publish(device, data);
    });

    device.on('accelerometerChange', function(x, y, z) {
        var data = {
            "sensor": "accelerometer",
            "accelX" : x,
            "accelY" : y,
            "accelZ" : z
        };
        publish(device, data);
    });

    device.on('magnetometerChange', function(x, y, z) {
        var data = {
            "sensor": "magnetometer",
            "magX" : x,
            "magY" : y,
            "magZ" : z
        };
        publish(device, data);
    });

    function initAirSensors() {
        device.enableIrTemperature();
        device.enableHumidity();
        device.enableBarometricPressure();
        var intervalId = setInterval(function() {
            if(!connected) {
                clearInterval(intervalId);
                return;
            }
            device.readBarometricPressure(function(pressure) {
                device.readHumidity(function(temperature, humidity) {
                    device.readIrTemperature(function(objectTemperature, ambientTemperature) {
                        var data = {
                            "sensor": "air",
                            "pressure" : pressure,
                            "humidity" : humidity,
                            "objTemp" : objectTemperature,
                            "ambientTemp" : ambientTemperature,
                            "temp" : temperature
                        };
                        publish(device, data);
                    });
                });
            });
        }, 5000);
    }
}

console.log('Make sure the Sensor Tag is on!');

SensorTag.discoverAll(onDiscover);<|endoftext|>


<commit_before>var mongodb = require('mongodb');

var host = "alex.mongohq.com";
var port = 10016;
var options = {};

var server = new mongodb.Server(host, port, options, {native_parser: true});
var Database = new mongodb.Db("TexasEstimateEm", server, {safe: false});

var inspect  = require('eyes').inspector({ stream: null });

exports.close = function(){
  Database.close();
};

exports.open = function(callback){
  console.log(inspect('Opening database...'));

  Database.open(function(error, db){

    if(error){return callback.call(this, error);}
    console.log(inspect('Authenticating...'));

    db.authenticate('narciso', 'guillen', function (err, replies) {
      console.log(inspect("We are now connected and authenticated ."));

      var collections = {
        users: new mongodb.Collection(db, "users"),
        tasks: new mongodb.Collection(db, "tasks")
      };

      return callback.call(this, err, collections);
    });

  });

};

<commit_msg>Use configuration values on database script<commit_after>var mongodb = require('mongodb');
var inspect  = require('eyes').inspector({ stream: null });

exports.close = function(){
  Database.close();
};

exports.open = function(database, callback){
  var connection = database.connection;
  var user       = database.user;

  var server = new mongodb.Server(connection.host, connection.port, connection.options, connection.native_parser);
  var Database = new mongodb.Db(database.name, server, {safe: false});

  console.log(inspect('Opening database...'));

  Database.open(function(error, db){

    if(error){return callback.call(this, error);}
    console.log(inspect('Authenticating...'));

    db.authenticate(user.username, user.password, function (err, replies) {
      console.log(inspect("We are now connected and authenticated ."));

      var collections = {
        users: new mongodb.Collection(db, "users"),
        tasks: new mongodb.Collection(db, "tasks")
      };

      return callback.call(this, err, collections);
    });

  });

};

<|endoftext|>


<commit_before>function MoodViewModel(value, img) {
    var self = this;

    self.value = value;
    self.img = img;
    self.siblings = [];
    self.flash = ko.observable("");

    self.sendMood = function (parentVM) {
        if (self.flash()) {
            return;
        }

        $.ajax({
            method: 'put',
            url: window.location.origin + "/Survey/Answer/" + window.location.href.split('/').pop(),
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ moodId: self.value, details: parentVM.details() }),
            success: function (answer) {
                self.flash("flash-green");
                parentVM.moods
                    .filter(function (mood) { return mood.value != self.value; })
                    .forEach(function (sibling) { sibling.flash("flash-fade"); });
                setTimeout(function () {
                    parentVM.moods.forEach(function (mood) { mood.flash(""); });
                }, 2000);
                parentVM.lastAnswer(answer);
            }
        });
    };

    return self;
}<commit_msg>Adding timeout mechanism to prevent people from submitting messages to the previous faces<commit_after>function MoodViewModel(value, img) {
    var self = this;

    self.value = value;
    self.img = img;
    self.siblings = [];
    self.flash = ko.observable("");

    self.sendMood = function (parentVM) {
        if (self.flash()) {
            return;
        }

        $.ajax({
            method: 'put',
            url: window.location.origin + "/Survey/Answer/" + window.location.href.split('/').pop(),
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ moodId: self.value, details: parentVM.details() }),
            success: function (answer) {
                self.flash("flash-green");
                parentVM.moods
                    .filter(function (mood) { return mood.value != self.value; })
                    .forEach(function (sibling) { sibling.flash("flash-fade"); });
                setTimeout(function () {
                    parentVM.moods.forEach(function (mood) { mood.flash(""); });
                }, 2000);

                // Check every 10 seconds; if the details are empty, the person is gone and we can clean up
                parentVM.lastAnswer(answer);
                function check() {
                    if (!parentVM.details()) {
                        parentVM.lastAnswer(null);
                    } else {
                        setTimeout(check, 10000);
                    }
                }
                setTimeout(check, 10000);
            }
        });
    };

    return self;
}<|endoftext|>