<commit_before>/*! EnhanceJS: a progressive enhancement boilerplate. Copyright 2014 @scottjehl, Filament Group, Inc. Licensed MIT */
(function( window, undefined ) {

	// Enable JS strict mode
	"use strict";

	var setTimeout = window.setTimeout;

	var enhance = {};

	// Define some variables to be used throughout this file
	var doc = window.document,
		docElem = doc.documentElement,
		head = doc.head || doc.getElementsByTagName( "head" )[ 0 ],
		// this references a meta tag's name whose content attribute should define the path to the full CSS file for the site
		fullCSSKey = "fullcss",
		// this references a meta tag's name whose content attribute should define the path to the enhanced JS file for the site (delivered to qualified browsers)
		fullJSKey = "fulljs",
		// this references a meta tag's name whose content attribute should define the path to the custom fonts file for the site (delivered to qualified browsers)
		fontsKey = "fonts",
		// classes to be added to the HTML element in qualified browsers
		htmlClasses = [ "enhanced", "ctm" ];

	/* Some commonly used functions - delete anything you don't need! */

	// loadJS: load a JS file asynchronously. Included from https://github.com/filamentgroup/loadJS/
	function loadJS( src ){
		var ref = window.document.getElementsByTagName( "script" )[ 0 ];
		var script = window.document.createElement( "script" );
		script.src = src;
		script.async = true;
		ref.parentNode.insertBefore( script, ref );
		return script;
	}

	// expose it
	enhance.loadJS = loadJS;

	// loadCSS: load a CSS file asynchronously. Included from https://github.com/filamentgroup/loadCSS/
	function loadCSS( href, before, media ){
		// Arguments explained:
		// `href` is the URL for your CSS file.
		// `before` optionally defines the element we'll use as a reference for injecting our <link>
		// By default, `before` uses the first <script> element in the page.
		// However, since the order in which stylesheets are referenced matters, you might need a more specific location in your document.
		// If so, pass a different reference element to the `before` argument and it'll insert before that instead
		// note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
		var ss = window.document.createElement( "link" );
		var ref = before || window.document.getElementsByTagName( "script" )[ 0 ];
		var sheets = window.document.styleSheets;
		ss.rel = "stylesheet";
		ss.href = href;
		// temporarily, set media to something non-matching to ensure it'll fetch without blocking render
		ss.media = "only x";
		// inject link
		ref.parentNode.insertBefore( ss, ref );
		// This function sets the link's media back to `all` so that the stylesheet applies once it loads
		// It is designed to poll until document.styleSheets includes the new sheet.
		function toggleMedia(){
			var defined;
			for( var i = 0; i < sheets.length; i++ ){
				if( sheets[ i ].href && sheets[ i ].href.indexOf( href ) > -1 ){
					defined = true;
				}
			}
			if( defined ){
				ss.media = media || "all";
			}
			else {
				setTimeout( toggleMedia );
			}
		}

		toggleMedia();
		return ss;
	}

	// expose it
	enhance.loadCSS = loadCSS;

	// getMeta function: get a meta tag by name
	// NOTE: meta tag must be in the HTML source before this script is included in order to guarantee it'll be found
	function getMeta( metaname ){
		var metas = window.document.getElementsByTagName( "meta" );
		var meta;
		for( var i = 0; i < metas.length; i ++ ){
			if( metas[ i ].name && metas[ i ].name === metaname ){
				meta = metas[ i ];
				break;
			}
		}
		return meta;
	}

	// expose it
	enhance.getMeta = getMeta;

	// cookie function from https://github.com/filamentgroup/cookie/
	function cookie( name, value, days ){
		var expires;
		// if value is undefined, get the cookie value
		if( value === undefined ){
			var cookiestring = "; " + window.document.cookie;
			var cookies = cookiestring.split( "; " + name + "=" );
			if ( cookies.length == 2 ){
				return cookies.pop().split( ";" ).shift();
			}
			return null;
		}
		else {
			// if value is a false boolean, we'll treat that as a delete
			if( value === false ){
				days = -1;
			}
			if ( days ) {
				var date = new Date();
				date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
				expires = "; expires="+date.toGMTString();
			}
			else {
				expires = "";
			}
			window.document.cookie = name + "=" + value + expires + "; path=/";
		}
	}

	// expose it
	enhance.cookie = cookie;

	/* Enhancements for all browsers - qualified or not */

	/* Load non-critical CSS async on first visit:
		On first visit to the site, the critical CSS for each template should be inlined in the head, while the full CSS for the site should be requested async and cached for later use.
		A meta tag with a name matching the fullCSSKey should have a content attribute referencing the path to the full CSS file for the site.
		If no cookie is set to specify that the full CSS has already been fetched, load it asynchronously and set the cookie.
		Once the cookie is set, the full CSS is assumed to be in cache, and the server-side templates should reference the full CSS directly from the head of the page with a link element, in place of inline critical styles.
		*/
	var fullCSS = getMeta( fullCSSKey );
	if( fullCSS && !cookie( fullCSSKey ) ){
		loadCSS( fullCSS.content );
		// set cookie to mark this file fetched
		cookie( fullCSSKey, "true", 7 );
	}

	/* Enhancements for qualified browsers - “Cutting the Mustard”
		Add your qualifications for major browser experience divisions here.
		For example, you might choose to only enhance browsers that support document.querySelector (IE8+, etc).
		Or you might choose to enhance browsers that support document.querySelector, localStorage and addEventListener (IE9+, etc).
		Use case will vary. More about BBC's ctm concpet here: http://responsivenews.co.uk/post/18948466399/cutting-the-mustard
		*/
	function ctm() {
		if("querySelector" in doc && "localStorage" in window && "addEventListener" in window ) {
			return true;
		}
		else {
			return false;
		}
	}

	// expose it
	enhance.ctm = ctm;

	if( !( ctm() ) ){
		// basic browsers: last stop here!
		return;
	}

	// From here on we're dealing with qualified browsers.

	// Add scoping classes to HTML element: useful for upgrading the presentation of elements that will be enhanced with JS behavior
	docElem.className += " " + htmlClasses.join(" ");

	/* Load JavaScript enhancements in one request.
		Your DOM framework and dependent component scripts should be concatenated and minified into one file that we'll load dynamically (keep that file as small as possible!)
		A meta tag with a name matching the fullJSKey should have a content attribute referencing the path to this JavaScript file.
		*/
	var fullJS = getMeta( fullJSKey );
	if( fullJS ){
		loadJS( fullJS.content );
	}

	/* Load custom fonts
		We prefer to load fonts asynchronously so that they do not block page rendering.
		To do this, a meta tag with a name matching the fontsWoffKey should have a content attribute referencing the path to this fonts file.
		NOTE: You may want to have logic here to choose between one of many font formats before loading it.
		For example, we often load WOFF, Truetype, or SVG. If so, just define meta tags for each
		*/
	var fonts = getMeta( fontsKey );
	if( fonts ){
		loadCSS( fonts.content );
	}

	// expose the 'enhance' object globally. Use it to expose anything in here that's useful to other parts of your application.
	window.enhance = enhance;

}( this ));
<commit_msg>Expose enhance variable to old browsers (for ctm check).<commit_after>/*! EnhanceJS: a progressive enhancement boilerplate. Copyright 2014 @scottjehl, Filament Group, Inc. Licensed MIT */
(function( window, undefined ) {

	// Enable JS strict mode
	"use strict";

	var setTimeout = window.setTimeout;

	var enhance = {};

	// Define some variables to be used throughout this file
	var doc = window.document,
		docElem = doc.documentElement,
		head = doc.head || doc.getElementsByTagName( "head" )[ 0 ],
		// this references a meta tag's name whose content attribute should define the path to the full CSS file for the site
		fullCSSKey = "fullcss",
		// this references a meta tag's name whose content attribute should define the path to the enhanced JS file for the site (delivered to qualified browsers)
		fullJSKey = "fulljs",
		// this references a meta tag's name whose content attribute should define the path to the custom fonts file for the site (delivered to qualified browsers)
		fontsKey = "fonts",
		// classes to be added to the HTML element in qualified browsers
		htmlClasses = [ "enhanced", "ctm" ];

	/* Some commonly used functions - delete anything you don't need! */

	// loadJS: load a JS file asynchronously. Included from https://github.com/filamentgroup/loadJS/
	function loadJS( src ){
		var ref = window.document.getElementsByTagName( "script" )[ 0 ];
		var script = window.document.createElement( "script" );
		script.src = src;
		script.async = true;
		ref.parentNode.insertBefore( script, ref );
		return script;
	}

	// expose it
	enhance.loadJS = loadJS;

	// loadCSS: load a CSS file asynchronously. Included from https://github.com/filamentgroup/loadCSS/
	function loadCSS( href, before, media ){
		// Arguments explained:
		// `href` is the URL for your CSS file.
		// `before` optionally defines the element we'll use as a reference for injecting our <link>
		// By default, `before` uses the first <script> element in the page.
		// However, since the order in which stylesheets are referenced matters, you might need a more specific location in your document.
		// If so, pass a different reference element to the `before` argument and it'll insert before that instead
		// note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
		var ss = window.document.createElement( "link" );
		var ref = before || window.document.getElementsByTagName( "script" )[ 0 ];
		var sheets = window.document.styleSheets;
		ss.rel = "stylesheet";
		ss.href = href;
		// temporarily, set media to something non-matching to ensure it'll fetch without blocking render
		ss.media = "only x";
		// inject link
		ref.parentNode.insertBefore( ss, ref );
		// This function sets the link's media back to `all` so that the stylesheet applies once it loads
		// It is designed to poll until document.styleSheets includes the new sheet.
		function toggleMedia(){
			var defined;
			for( var i = 0; i < sheets.length; i++ ){
				if( sheets[ i ].href && sheets[ i ].href.indexOf( href ) > -1 ){
					defined = true;
				}
			}
			if( defined ){
				ss.media = media || "all";
			}
			else {
				setTimeout( toggleMedia );
			}
		}

		toggleMedia();
		return ss;
	}

	// expose it
	enhance.loadCSS = loadCSS;

	// getMeta function: get a meta tag by name
	// NOTE: meta tag must be in the HTML source before this script is included in order to guarantee it'll be found
	function getMeta( metaname ){
		var metas = window.document.getElementsByTagName( "meta" );
		var meta;
		for( var i = 0; i < metas.length; i ++ ){
			if( metas[ i ].name && metas[ i ].name === metaname ){
				meta = metas[ i ];
				break;
			}
		}
		return meta;
	}

	// expose it
	enhance.getMeta = getMeta;

	// cookie function from https://github.com/filamentgroup/cookie/
	function cookie( name, value, days ){
		var expires;
		// if value is undefined, get the cookie value
		if( value === undefined ){
			var cookiestring = "; " + window.document.cookie;
			var cookies = cookiestring.split( "; " + name + "=" );
			if ( cookies.length == 2 ){
				return cookies.pop().split( ";" ).shift();
			}
			return null;
		}
		else {
			// if value is a false boolean, we'll treat that as a delete
			if( value === false ){
				days = -1;
			}
			if ( days ) {
				var date = new Date();
				date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
				expires = "; expires="+date.toGMTString();
			}
			else {
				expires = "";
			}
			window.document.cookie = name + "=" + value + expires + "; path=/";
		}
	}

	// expose it
	enhance.cookie = cookie;

	/* Enhancements for all browsers - qualified or not */

	/* Load non-critical CSS async on first visit:
		On first visit to the site, the critical CSS for each template should be inlined in the head, while the full CSS for the site should be requested async and cached for later use.
		A meta tag with a name matching the fullCSSKey should have a content attribute referencing the path to the full CSS file for the site.
		If no cookie is set to specify that the full CSS has already been fetched, load it asynchronously and set the cookie.
		Once the cookie is set, the full CSS is assumed to be in cache, and the server-side templates should reference the full CSS directly from the head of the page with a link element, in place of inline critical styles.
		*/
	var fullCSS = getMeta( fullCSSKey );
	if( fullCSS && !cookie( fullCSSKey ) ){
		loadCSS( fullCSS.content );
		// set cookie to mark this file fetched
		cookie( fullCSSKey, "true", 7 );
	}

	/* Enhancements for qualified browsers - “Cutting the Mustard”
		Add your qualifications for major browser experience divisions here.
		For example, you might choose to only enhance browsers that support document.querySelector (IE8+, etc).
		Or you might choose to enhance browsers that support document.querySelector, localStorage and addEventListener (IE9+, etc).
		Use case will vary. More about BBC's ctm concpet here: http://responsivenews.co.uk/post/18948466399/cutting-the-mustard
		*/
	function ctm() {
		if("querySelector" in doc && "localStorage" in window && "addEventListener" in window ) {
			return true;
		}
		else {
			return false;
		}
	}

	// expose it
	enhance.ctm = ctm;

	if( !( ctm() ) ){
		// basic browsers: last stop here!
		window.enhance = enhance; // expose enhance to window, to use in older browsers
		return;
	}

	// From here on we're dealing with qualified browsers.

	// Add scoping classes to HTML element: useful for upgrading the presentation of elements that will be enhanced with JS behavior
	docElem.className += " " + htmlClasses.join(" ");

	/* Load JavaScript enhancements in one request.
		Your DOM framework and dependent component scripts should be concatenated and minified into one file that we'll load dynamically (keep that file as small as possible!)
		A meta tag with a name matching the fullJSKey should have a content attribute referencing the path to this JavaScript file.
		*/
	var fullJS = getMeta( fullJSKey );
	if( fullJS ){
		loadJS( fullJS.content );
	}

	/* Load custom fonts
		We prefer to load fonts asynchronously so that they do not block page rendering.
		To do this, a meta tag with a name matching the fontsWoffKey should have a content attribute referencing the path to this fonts file.
		NOTE: You may want to have logic here to choose between one of many font formats before loading it.
		For example, we often load WOFF, Truetype, or SVG. If so, just define meta tags for each
		*/
	var fonts = getMeta( fontsKey );
	if( fonts ){
		loadCSS( fonts.content );
	}

	// expose the 'enhance' object globally. Use it to expose anything in here that's useful to other parts of your application.
	window.enhance = enhance;

}( this ));
<|endoftext|>


<commit_before>/*global print */
'use strict';

var runTest = require('jsunity').runTest,
  _ = require('underscore'),
  internal = require('internal');

////////////////////////////////////////////////////////////////////////////////
/// @brief runs all jsunity tests
////////////////////////////////////////////////////////////////////////////////

function runJSUnityTests(tests) {
  var result = true;
  var allResults = [];
  var res;

  // find out whether we're on server or client...
  var runenvironment = "arangod";
  if (typeof(require('internal').arango) === 'object') {
    runenvironment = "arangosh";
  }

  _.each(tests, function (file) {
    if (result) {
      print("\n" + Date() + " " + runenvironment + ": Running JSUnity test from file '" + file + "'");
    } else {
      print("\n" + Date() + " " + runenvironment +
            ": Skipping JSUnity test from file '" + file + "' due to previous errors");
    }

    try {
      res = runTest(file, true);
      allResults.push(res);
      result = result && res.status;
    } catch (err) {
      print(runenvironment + ": cannot run test file '" + file + "': " + err);
      print(err.stack);
      print(err.message);
      result = false;
    }

    internal.wait(0); // force GC
  });
  require("fs").write("testresult.json", JSON.stringify(allResults));
  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief runs all jsunity tests
////////////////////////////////////////////////////////////////////////////////

function runJasmineTests(testFiles, options) {
  var result = true;

  if (testFiles.length > 0) {
    print('\nRunning Jasmine Tests: ' + testFiles.join(', '));
    result = require('jasmine').executeTestSuite(testFiles, options);
  }

  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief runs tests from command-line
////////////////////////////////////////////////////////////////////////////////

function runCommandLineTests(opts) {
  var result = true,
    options = opts || {},
    jasmineReportFormat = options.jasmineReportFormat || 'progress',
    unitTests = internal.unitTests(),
    isSpecRegEx = /.+-spec.*\.js/,
    isSpec = function (unitTest) {
      return isSpecRegEx.test(unitTest);
    },
    jasmine = _.filter(unitTests, isSpec),
    jsUnity = _.reject(unitTests, isSpec);

  result = runJSUnityTests(jsUnity) && runJasmineTests(jasmine, { format: jasmineReportFormat });

  internal.setUnitTestsResult(result);
}

exports.runCommandLineTests = runCommandLineTests;
<commit_msg>print names of files with failing tests<commit_after>/*global print */
'use strict';

var runTest = require('jsunity').runTest,
  _ = require('underscore'),
  internal = require('internal');

////////////////////////////////////////////////////////////////////////////////
/// @brief runs all jsunity tests
////////////////////////////////////////////////////////////////////////////////

function runJSUnityTests(tests) {
  var result = true;
  var allResults = [];
  var failed = [];
  var res;

  // find out whether we're on server or client...
  var runenvironment = "arangod";
  if (typeof(require('internal').arango) === 'object') {
    runenvironment = "arangosh";
  }

  _.each(tests, function (file) {
    if (result) {
      print("\n" + Date() + " " + runenvironment + ": Running JSUnity test from file '" + file + "'");
    }
    else {
      print("\n" + Date() + " " + runenvironment +
            ": Skipping JSUnity test from file '" + file + "' due to previous errors");
    }

    try {
      res = runTest(file, true);
      allResults.push(res);
      result = result && res.status;
      if (! res.status) {
        failed.push(file);
      }
    }
    catch (err) {
      print(runenvironment + ": cannot run test file '" + file + "': " + err);
      print(err.stack);
      print(err.message);
      result = false;
    }

    internal.wait(0); // force GC
  });
  require("fs").write("testresult.json", JSON.stringify(allResults));

  if (failed.length > 1) {
    print("The following test files produced errors: ", failed.join(", "));
  }
  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief runs all jsunity tests
////////////////////////////////////////////////////////////////////////////////

function runJasmineTests(testFiles, options) {
  var result = true;

  if (testFiles.length > 0) {
    print('\nRunning Jasmine Tests: ' + testFiles.join(', '));
    result = require('jasmine').executeTestSuite(testFiles, options);
  }

  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief runs tests from command-line
////////////////////////////////////////////////////////////////////////////////

function runCommandLineTests(opts) {
  var result = true,
    options = opts || {},
    jasmineReportFormat = options.jasmineReportFormat || 'progress',
    unitTests = internal.unitTests(),
    isSpecRegEx = /.+-spec.*\.js/,
    isSpec = function (unitTest) {
      return isSpecRegEx.test(unitTest);
    },
    jasmine = _.filter(unitTests, isSpec),
    jsUnity = _.reject(unitTests, isSpec);

  result = runJSUnityTests(jsUnity) && runJasmineTests(jasmine, { format: jasmineReportFormat });

  internal.setUnitTestsResult(result);
}

exports.runCommandLineTests = runCommandLineTests;
<|endoftext|>


<commit_before>/**
 * jQuery plugin paroller.js v1.3.0
 * https://github.com/tgomilar/paroller.js
 * preview: https://tgomilar.github.io/paroller/
 **/
(function (factory) {
    'use strict';

    if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = factory(require('jquery'));
    }
    else {
        factory(jQuery);
    }
})(function ($) {
    'use strict';

    var setDirection = {
        bgVertical: function (elem, bgOffset) {
            return elem.css({'background-position': 'center ' + -bgOffset + 'px'});
        },
        bgHorizontal: function (elem, bgOffset) {
            return elem.css({'background-position': -bgOffset + 'px' + ' center'});
        },
        vertical: function (elem, elemOffset, oldTransform) {
            (oldTransform === 'none' ? oldTransform = '' : true);
            return elem.css({
                '-webkit-transform': 'translateY(' + elemOffset + 'px)' + oldTransform,
                '-moz-transform': 'translateY(' + elemOffset + 'px)' + oldTransform,
                'transform': 'translateY(' + elemOffset + 'px)' + oldTransform,
                'transition': 'transform linear',
                'will-change': 'transform'
            });
        },
        horizontal: function (elem, elemOffset, oldTransform) {
            (oldTransform === 'none' ? oldTransform = '' : true);
            return elem.css({
                '-webkit-transform': 'translateX(' + elemOffset + 'px)' + oldTransform,
                '-moz-transform': 'translateX(' + elemOffset + 'px)' + oldTransform,
                'transform': 'translateX(' + elemOffset + 'px)' + oldTransform,
                'transition': 'transform linear',
                'will-change': 'transform'
            });
        }
    };

    $.fn.paroller = function (options) {
        var windowHeight = $(window).height();
        var documentHeight = $(document).height();

        // default options
        var options = $.extend({
            factor: 0, // - to +
            type: 'background', // foreground
            direction: 'vertical' // horizontal
        }, options);

        return this.each(function () {
            var working = false;
            var $this = $(this);
            var offset = $this.offset().top;
            var height = $this.outerHeight();
            var dataFactor = $this.data('paroller-factor');
            var dataType = $this.data('paroller-type');
            var dataDirection = $this.data('paroller-direction');

            var factor = (dataFactor) ? dataFactor : options.factor;
            var type = (dataType) ? dataType : options.type;
            var direction = (dataDirection) ? dataDirection : options.direction;
            var bgOffset = Math.round(offset * factor);
            var transform = Math.round((offset - (windowHeight / 2) + height) * factor);

            /* Transform directive of element before paroller */
            var oldTransform = $this.css('transform');

            if (type == 'background') {
                if (direction == 'vertical') {
                    setDirection.bgVertical($this, bgOffset);
                }
                else if (direction == 'horizontal') {
                    setDirection.bgHorizontal($this, bgOffset);
                }
            }
            else if (type == 'foreground') {
                if (direction == 'vertical') {
                    setDirection.vertical($this, transform, oldTransform);
                }
                else if (direction == 'horizontal') {
                    setDirection.horizontal($this, transform, oldTransform);
                }
            }

            var scrollAction = function () {
                working = false;
            };

            $(window).on('scroll', function () {
                if (!working) {
                    var scrolling = $(this).scrollTop();
                    documentHeight = $(document).height();

                    bgOffset = Math.round((offset - scrolling) * factor);
                    transform = Math.round(((offset - (windowHeight / 2) + height) - scrolling) * factor);

                    if (type == 'background') {
                        if (direction == 'vertical') {
                            setDirection.bgVertical($this, bgOffset);
                        }
                        else if (direction == 'horizontal') {
                            setDirection.bgHorizontal($this, bgOffset);
                        }
                    }
                    else if ((type == 'foreground') && (scrolling <= documentHeight)) {
                        if (direction == 'vertical') {
                            setDirection.vertical($this, transform, oldTransform);
                        }
                        else if (direction == 'horizontal') {
                            setDirection.horizontal($this, transform, oldTransform);
                        }
                    }

                    window.requestAnimationFrame(scrollAction);
                    working = true;
                }
            }).trigger('scroll');
        });
    };
});<commit_msg>comment corrected to  v1.3.1<commit_after>/**
 * jQuery plugin paroller.js v1.3.1
 * https://github.com/tgomilar/paroller.js
 * preview: https://tgomilar.github.io/paroller/
 **/
(function (factory) {
    'use strict';

    if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = factory(require('jquery'));
    }
    else {
        factory(jQuery);
    }
})(function ($) {
    'use strict';

    var setDirection = {
        bgVertical: function (elem, bgOffset) {
            return elem.css({'background-position': 'center ' + -bgOffset + 'px'});
        },
        bgHorizontal: function (elem, bgOffset) {
            return elem.css({'background-position': -bgOffset + 'px' + ' center'});
        },
        vertical: function (elem, elemOffset, oldTransform) {
            (oldTransform === 'none' ? oldTransform = '' : true);
            return elem.css({
                '-webkit-transform': 'translateY(' + elemOffset + 'px)' + oldTransform,
                '-moz-transform': 'translateY(' + elemOffset + 'px)' + oldTransform,
                'transform': 'translateY(' + elemOffset + 'px)' + oldTransform,
                'transition': 'transform linear',
                'will-change': 'transform'
            });
        },
        horizontal: function (elem, elemOffset, oldTransform) {
            (oldTransform === 'none' ? oldTransform = '' : true);
            return elem.css({
                '-webkit-transform': 'translateX(' + elemOffset + 'px)' + oldTransform,
                '-moz-transform': 'translateX(' + elemOffset + 'px)' + oldTransform,
                'transform': 'translateX(' + elemOffset + 'px)' + oldTransform,
                'transition': 'transform linear',
                'will-change': 'transform'
            });
        }
    };

    $.fn.paroller = function (options) {
        var windowHeight = $(window).height();
        var documentHeight = $(document).height();

        // default options
        var options = $.extend({
            factor: 0, // - to +
            type: 'background', // foreground
            direction: 'vertical' // horizontal
        }, options);

        return this.each(function () {
            var working = false;
            var $this = $(this);
            var offset = $this.offset().top;
            var height = $this.outerHeight();
            var dataFactor = $this.data('paroller-factor');
            var dataType = $this.data('paroller-type');
            var dataDirection = $this.data('paroller-direction');

            var factor = (dataFactor) ? dataFactor : options.factor;
            var type = (dataType) ? dataType : options.type;
            var direction = (dataDirection) ? dataDirection : options.direction;
            var bgOffset = Math.round(offset * factor);
            var transform = Math.round((offset - (windowHeight / 2) + height) * factor);

            /* Transform directive of element before paroller */
            var oldTransform = $this.css('transform');

            if (type == 'background') {
                if (direction == 'vertical') {
                    setDirection.bgVertical($this, bgOffset);
                }
                else if (direction == 'horizontal') {
                    setDirection.bgHorizontal($this, bgOffset);
                }
            }
            else if (type == 'foreground') {
                if (direction == 'vertical') {
                    setDirection.vertical($this, transform, oldTransform);
                }
                else if (direction == 'horizontal') {
                    setDirection.horizontal($this, transform, oldTransform);
                }
            }

            var scrollAction = function () {
                working = false;
            };

            $(window).on('scroll', function () {
                if (!working) {
                    var scrolling = $(this).scrollTop();
                    documentHeight = $(document).height();

                    bgOffset = Math.round((offset - scrolling) * factor);
                    transform = Math.round(((offset - (windowHeight / 2) + height) - scrolling) * factor);

                    if (type == 'background') {
                        if (direction == 'vertical') {
                            setDirection.bgVertical($this, bgOffset);
                        }
                        else if (direction == 'horizontal') {
                            setDirection.bgHorizontal($this, bgOffset);
                        }
                    }
                    else if ((type == 'foreground') && (scrolling <= documentHeight)) {
                        if (direction == 'vertical') {
                            setDirection.vertical($this, transform, oldTransform);
                        }
                        else if (direction == 'horizontal') {
                            setDirection.horizontal($this, transform, oldTransform);
                        }
                    }

                    window.requestAnimationFrame(scrollAction);
                    working = true;
                }
            }).trigger('scroll');
        });
    };
});<|endoftext|>


<commit_before>var task_ids = {}

function setProgress(progress_id, value, maxvalue){
	var progressField = $('#' + progress_id);
	var progressBar = progressField.children('.progress-bar');
	var progressText = progressField.children('.progress-text');

	if(value > 0 && value == maxvalue){
		progressBar.css('width', progressField.width() + "px");
		progressText.html('Complete!');
	}
	else if(value == 0){
		progressBar.css('width', 0);
		progressText.html('Waiting...');
	}
	else if(value == -1){
		progressText.html('Error!');
	}
	else{
		var percent = value / maxvalue;
		var client_width = progressField.width();
		var width = Math.round(percent * client_width) + "px";

		progressBar.css('width', width);
		progressText.html(Math.round(percent * 100) + '%');
	}
}

function waitForCompletion(progress_id, callback_url, interval){
	var progressField = $('#' + progress_id);
	var progressText = progressField.children('.progress-text');

	progressText.html('0%');
	task_id = setInterval(checkProgress, interval, callback_url, progress_id);
	task_ids[progress_id] = task_id;
}

function checkProgress(callback_url, progress_id){
	jQuery.ajax({
		url: 		callback_url + '/' + progress_id,
		datatype:	'text',
		success:	function(data, textStatus){
						checkProgressCallback(data, textStatus, progress_id);
					},
		error:		function(request, textStatus, errorThrown){
						checkProgressErrback(request, textStatus, errorThrown, progress_id);
					}
	});
}

function checkProgressCallback(data, textStatus, progress_id){
	var stats = data.split('/');
	var value = parseInt(stats[0]);
	var maxvalue = parseInt(stats[1]);

	if(value > 0 && value == maxvalue){
		clearInterval(task_ids[progress_id])
		delete task_ids[progress_id];
	}

	setProgress(progress_id, value, maxvalue);
}

function checkProgressErrback(request, textStatus, errorThrown, progress_id) {
	stopProgressBar(progress_id, true);
}

function stopProgressBar(progress_id, is_error){
	if(is_error){
		setProgress(progress_id, -1, 0);
	}

	if(task_ids[progress_id]){
		clearInterval(task_ids[progress_id])
		delete task_ids[progress_id];
	}
}
<commit_msg>progressbar cleanup<commit_after>var task_ids = {}

function setProgress(progress_id, value, maxvalue){
	var progressField = $('#' + progress_id);
	var progressBar = progressField.children('.progress-bar');
	var progressText = progressField.children('.progress-text');

	if(value > 0 && value == maxvalue){
		progressBar.css('width', progressField.width() + "px");
		progressText.html('Complete!');
	}
	else if(value == 0){
		progressBar.css('width', 0);
		progressText.html('Waiting...');
	}
	else if(value == -1){
		progressText.html('Error!');
	}
	else{
		var percent = value / maxvalue;
		var client_width = progressField.width();
		var width = Math.round(percent * client_width) + "px";

		progressBar.css('width', width);
		progressText.html(Math.round(percent * 100) + '%');
	}
}

function waitForCompletion(progress_id, callback_url, interval){
	var progressField = $('#' + progress_id);
	var progressText = progressField.children('.progress-text');

	progressText.html('0%');
	task_id = setInterval(checkProgress, interval, callback_url, progress_id);
	task_ids[progress_id] = task_id;
}

function checkProgress(callback_url, progress_id){
	jQuery.ajax({
		url: 		callback_url + '/' + progress_id,
		datatype:	'text',
		success:	function(data, textStatus){
						checkProgressCallback(data, textStatus, progress_id);
					},
		error:		function(request, textStatus, errorThrown){
						checkProgressErrback(request, textStatus, errorThrown, progress_id);
					}
	});
}

function checkProgressCallback(data, textStatus, progress_id){
	var stats = data.split('/');
	var value = parseInt(stats[0]);
	var maxvalue = parseInt(stats[1]);

	if(value > 0 && value == maxvalue){
		stopProgressBar(progress_id, false);
	}

	setProgress(progress_id, value, maxvalue);
}

function checkProgressErrback(request, textStatus, errorThrown, progress_id) {
	stopProgressBar(progress_id, true);
}

function stopProgressBar(progress_id, is_error){
	if(is_error){
		setProgress(progress_id, -1, 0);
	}

	if(task_ids[progress_id]){
		clearInterval(task_ids[progress_id])
		delete task_ids[progress_id];
	}
}
<|endoftext|>


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

    function reset() {
        FD.resetResults();
        $('#form-modexp').trigger('reset');
    }

    $('#btn-calculate').click(function () {
        var data;
        try {
            data = FD.parseFields();
        } catch (e) {
            alert('Error: ' + e);
            return;
        }

        if (data.modexps.length === 0) {
            alert('Nothing to do!');
        } else if (data.modexps.length === 1) {
            if (data.defaultBase !== undefined || data.defaultExponent !== undefined || data.defaultModulus !== undefined) {
                alert('Default values not applicable for single modexp!');
                return;
            }

            FD.showResults();

            // local performance measurement
            var timeLocal = performance.now();
            var resultLocal = BigInt.modexp(data.modexps[0][0], data.modexps[0][1], data.modexps[0][2]);
            timeLocal = performance.now() - timeLocal;
            FD.showLocalTime(timeLocal);
            FD.showLocalResult(resultLocal);

            // remote performance measurement
            var famodulus = new Famodulus([FD.getServer('#input-server-1')], $('#input-brief').is(':checked'));
            var timeRemote = performance.now();
            famodulus.modexp(data.modexps[0][0], data.modexps[0][1], data.modexps[0][2], function (result) {
                timeRemote = performance.now() - timeRemote;

                if (timeRemote < timeLocal) {
                    FD.showRemoteTime(timeRemote, true);
                    FD.showLocalTime(timeLocal, false);
                } else if (timeRemote > timeLocal) {
                    FD.showRemoteTime(timeRemote, false);
                    FD.showLocalTime(timeLocal, true);
                } else {
                    FD.showRemoteTime(timeRemote);
                }
                FD.showRemoteResult(result);
                FD.showDifference(timeRemote, timeLocal);
                FD.showEqual(result, resultLocal);
            });
        } else {
            alert('Not implemented yet!');
        }
    });

    $('#btn-reset').click(function () {
        reset();
    });

    $('#btn-verificatum').click(function () {
        FD.injectVerificatum();
        alert('Verificatum library injected!');
    });

    $('#btn-add-p').click(function () {
        FD.appendTo('#input-bases', FD.randHexString());
        FD.appendTo('#input-exponents', FD.randHexString());
        FD.appendTo('#input-moduli', FD.P_3072);
    });

    $('#btn-add-rand').click(function () {
        FD.appendTo('#input-bases', FD.randHexString());
        FD.appendTo('#input-exponents', FD.randHexString());
        FD.appendTo('#input-moduli', FD.randHexString());
    });

    $('#btn-base-rand').click(function () {
        $('#input-base-default').val(FD.randHexString());
    });

    $('#btn-exponent-rand').click(function () {
        $('#input-exponent-default').val(FD.randHexString());
    });

    $('#btn-modulus-rand').click(function () {
        $('#input-modulus-default').val(FD.randHexString());
    });

    $('#btn-modulus-p').click(function () {
        $('#input-modulus-default').val(FD.P_3072);
    });

    reset();
    $('#input-server-1').attr('placeholder', FD.DEFAULT_SERVER);
});<commit_msg>changed to new result format, resetting verificatum button<commit_after>$('document').ready(function () {
    'use strict';

    function reset() {
        FD.resetResults();
        $('#form-modexp').trigger('reset');
    }

    $('#btn-calculate').click(function () {
        var data;
        try {
            data = FD.parseFields();
        } catch (e) {
            alert('Error: ' + e);
            return;
        }

        if (data.modexps.length === 0) {
            alert('Nothing to do!');
        } else if (data.modexps.length === 1) {
            if (data.defaultBase !== undefined || data.defaultExponent !== undefined || data.defaultModulus !== undefined) {
                alert('Default values not applicable for single modexp!');
                return;
            }

            FD.showResults();

            // local performance measurement
            var timeLocal = performance.now();
            var resultLocal = BigInt.modexp(data.modexps[0][0], data.modexps[0][1], data.modexps[0][2]);
            timeLocal = performance.now() - timeLocal;
            FD.showLocalTime(timeLocal);
            FD.showLocalResult(resultLocal);

            // remote performance measurement
            var famodulus = new Famodulus([FD.getServer('#input-server-1')], $('#input-brief').is(':checked'));
            var timeRemote = performance.now();
            famodulus.modexp(data.modexps[0][0], data.modexps[0][1], data.modexps[0][2], function (result) {
                timeRemote = performance.now() - timeRemote;

                if (timeRemote < timeLocal) {
                    FD.showRemoteTime(timeRemote, true);
                    FD.showLocalTime(timeLocal, false);
                } else if (timeRemote > timeLocal) {
                    FD.showRemoteTime(timeRemote, false);
                    FD.showLocalTime(timeLocal, true);
                } else {
                    FD.showRemoteTime(timeRemote);
                }
                FD.showRemoteResult(result.r);
                FD.showDifference(timeRemote, timeLocal);
                FD.showEqual(result.r, resultLocal);
            });
        } else {
            alert('Not implemented yet!');
        }
    });

    $('#btn-reset').click(function () {
        reset();
    });

    $('#btn-verificatum').click(function () {
        FD.injectVerificatum();
        alert('Verificatum library injected!');
    });

    $('#btn-add-p').click(function () {
        FD.appendTo('#input-bases', FD.randHexString());
        FD.appendTo('#input-exponents', FD.randHexString());
        FD.appendTo('#input-moduli', FD.P_3072);
    });

    $('#btn-add-rand').click(function () {
        FD.appendTo('#input-bases', FD.randHexString());
        FD.appendTo('#input-exponents', FD.randHexString());
        FD.appendTo('#input-moduli', FD.randHexString());
    });

    $('#btn-base-rand').click(function () {
        $('#input-base-default').val(FD.randHexString());
    });

    $('#btn-exponent-rand').click(function () {
        $('#input-exponent-default').val(FD.randHexString());
    });

    $('#btn-modulus-rand').click(function () {
        $('#input-modulus-default').val(FD.randHexString());
    });

    $('#btn-modulus-p').click(function () {
        $('#input-modulus-default').val(FD.P_3072);
    });

    reset();
    $('#input-server-1').attr('placeholder', FD.DEFAULT_SERVER);

    if(typeof(verificatum) !== 'undefined') {
        $('#btn-verificatum').prop('disabled', true);
    } else {
        $('#btn-verificatum').prop('disabled', false);
    }
});<|endoftext|>


<commit_before>export default async function deleteSession () {
    const pages = await this.browser.pages()

    /**
     * close all tabs
     */
    for (const page of pages) {
        await page.close()
    }

    await this.browser.close()
    return null
}
<commit_msg>minor tweak in deleteSession (#4432)<commit_after>export default async function deleteSession () {
    await this.browser.close()
    return null
}
<|endoftext|>


<commit_before>'use strict'

const co = require('co')
const cli = require('heroku-cli-util')

function * run (context, heroku) {
  const host = require('../../lib/host')
  const fetcher = require('../../lib/fetcher')(heroku)
  const util = require('../../lib/util')
  const {app, args, flags} = context
  let db = yield fetcher.addon(app, args.database)
  let all = flags.all
  let warnings = []
  let cred = flags.name || 'default'

  if (all && flags.name !== undefined) {
    throw new Error('cannot pass both --all and --name')
  }
  if (util.starterPlan(db) && cred !== 'default') {
    throw new Error(`Only one default credential is supported for Hobby tier databases.`)
  }
  if (all && flags.force) {
    warnings.push('This forces rotation on all credentials including the default credential.')
  }
  let attachments = yield heroku.get(`/addons/${db.name}/addon-attachments`)
  if (flags.name) {
    attachments = attachments.filter(a => a.namespace === `credential:${cred}`)
  }

  if (!flags.all) {
    warnings.push(`The password for the ${cred} credential will rotate.`)
  }
  if (flags.all || flags.force || cred === 'default') {
    warnings.push(`Connections will be reset and applications will be restarted.`)
  } else {
    warnings.push(`Connections older than 30 minutes will be reset, and a temporary rotation username will be used during the process.`)
  }
  if (attachments.length > 0) {
    warnings.push(`This command will affect the app${(attachments.length > 1) ? 's' : ''} ${[...new Set(attachments.map(c => cli.color.app(c.app.name)))].sort().join(', ')}.`)
  }

  yield cli.confirmApp(app, flags.confirm, `WARNING: Destructive Action
${warnings.join('\n')}`)

  let body = flags.force ? {host: host(db), force: true} : {host: host(db)}

  if (all) {
    yield cli.action(`Rotating all credentials on ${cli.color.addon(db.name)}`, co(function * () {
      yield heroku.post(`/postgres/v0/databases/${db.name}/credentials_rotation`,
        body)
    }))
  } else {
    yield cli.action(`Rotating ${cred} on ${cli.color.addon(db.name)}`, co(function * () {
      yield heroku.post(`/postgres/v0/databases/${db.name}/credentials/${encodeURIComponent(cred)}/credentials_rotation`,
        body)
    }))
  }
}

module.exports = {
  topic: 'pg',
  command: 'credentials:rotate',
  description: 'rotate the database credentials',
  needsApp: true,
  needsAuth: true,
  flags: [
    {name: 'name', char: 'n', description: 'which credential to rotate (default credentials if not specified)', hasValue: true},
    {name: 'all', description: 'rotate all credentials', hasValue: false},
    {name: 'confirm', char: 'c', hasValue: true},
    {name: 'force', description: 'forces rotating the targeted credentials', hasValue: false}
  ],
  args: [{name: 'database', optional: true}],
  run: cli.command({preauth: true}, co.wrap(run))
}
<commit_msg>fix(pg): changes 'force' to 'forced' (#945)<commit_after>'use strict'

const co = require('co')
const cli = require('heroku-cli-util')

function * run (context, heroku) {
  const host = require('../../lib/host')
  const fetcher = require('../../lib/fetcher')(heroku)
  const util = require('../../lib/util')
  const {app, args, flags} = context
  let db = yield fetcher.addon(app, args.database)
  let all = flags.all
  let warnings = []
  let cred = flags.name || 'default'

  if (all && flags.name !== undefined) {
    throw new Error('cannot pass both --all and --name')
  }
  if (util.starterPlan(db) && cred !== 'default') {
    throw new Error(`Only one default credential is supported for Hobby tier databases.`)
  }
  if (all && flags.force) {
    warnings.push('This forces rotation on all credentials including the default credential.')
  }
  let attachments = yield heroku.get(`/addons/${db.name}/addon-attachments`)
  if (flags.name) {
    attachments = attachments.filter(a => a.namespace === `credential:${cred}`)
  }

  if (!flags.all) {
    warnings.push(`The password for the ${cred} credential will rotate.`)
  }
  if (flags.all || flags.force || cred === 'default') {
    warnings.push(`Connections will be reset and applications will be restarted.`)
  } else {
    warnings.push(`Connections older than 30 minutes will be reset, and a temporary rotation username will be used during the process.`)
  }
  if (attachments.length > 0) {
    warnings.push(`This command will affect the app${(attachments.length > 1) ? 's' : ''} ${[...new Set(attachments.map(c => cli.color.app(c.app.name)))].sort().join(', ')}.`)
  }

  yield cli.confirmApp(app, flags.confirm, `WARNING: Destructive Action
${warnings.join('\n')}`)

  let body = flags.force ? {host: host(db), forced: true} : {host: host(db)}
  if (all) {
    yield cli.action(`Rotating all credentials on ${cli.color.addon(db.name)}`, co(function * () {
      yield heroku.post(`/postgres/v0/databases/${db.name}/credentials_rotation`,
        body)
    }))
  } else {
    yield cli.action(`Rotating ${cred} on ${cli.color.addon(db.name)}`, co(function * () {
      yield heroku.post(`/postgres/v0/databases/${db.name}/credentials/${encodeURIComponent(cred)}/credentials_rotation`,
        body)
    }))
  }
}

module.exports = {
  topic: 'pg',
  command: 'credentials:rotate',
  description: 'rotate the database credentials',
  needsApp: true,
  needsAuth: true,
  flags: [
    {name: 'name', char: 'n', description: 'which credential to rotate (default credentials if not specified)', hasValue: true},
    {name: 'all', description: 'rotate all credentials', hasValue: false},
    {name: 'confirm', char: 'c', hasValue: true},
    {name: 'force', description: 'forces rotating the targeted credentials', hasValue: false}
  ],
  args: [{name: 'database', optional: true}],
  run: cli.command({preauth: true}, co.wrap(run))
}
<|endoftext|>


<commit_before>'use strict';

viewModel.DatabrowserEvent = new Object();
var dbe = viewModel.DatabrowserEvent;

dbe.InitEventGrid = function() {
    dbr.eventrawvis(true);

    var turbine = [];
    if ($("#turbineList").data("kendoMultiSelect").value().indexOf("All Turbine") >= 0) {
        turbine = turbineval;
    } else {
        turbine = $("#turbineList").data("kendoMultiSelect").value();
    }

    var filters = [{
        field: "timestamp",
        operator: "gte",
        value: fa.dateStart
    }, {
        field: "timestamp",
        operator: "lte",
        value: fa.dateEnd
    }, {
        field: "turbine",
        operator: "in",
        value: turbine
    }, ];

    if(fa.project != "") {
        filters.push({
            field: "projectname",
            operator: "eq",
            value: fa.project
        })
    }

    $('#EventGrid').html("");
    $('#EventGrid').kendoGrid({
        dataSource: {
            serverPaging: true,
            serverSorting: true,
            serverFiltering: true,
            filter: filters,
            transport: {
                read: {
                    url: viewModel.appName + "databrowser/geteventlist",
                    type: "POST",
                    data: {},
                    dataType: "json",
                    contentType: "application/json; charset=utf-8"
                },
                parameterMap: function(options) {
                    return JSON.stringify(options);
                }
            },
            pageSize: 10,
            schema: {
                data: function(res) {
                    // app.loading(false);
                    dbr.eventrawvis(false);
                    return res.data.Data
                },
                total: function(res) {
                    if (!app.isFine(res)) {
                        return;
                    }

                    $('#totalturbineEvent').html(kendo.toString(res.data.TotalTurbine, 'n0'));
                    $('#totaldataEvent').html(kendo.toString(res.data.Total, 'n0'));

                    return res.data.Total;
                }
            },
            sort: [{
                field: 'TimeStamp',
                dir: 'asc'
            }, {
                field: 'Turbine',
                dir: 'asc'
            }],
        },
        selectable: "multiple",
        groupable: false,
        sortable: true,
        pageable: {
            pageSize: 10,
            input:true,
        },
        columns: [{
            title: "Time Stamp",
            field: "TimeStamp",
            template: "#= kendo.toString(moment.utc(TimeStamp).format('DD-MMM-YYYY HH:mm:ss'), 'dd-MMM-yyyy HH:mm:ss') #",
            width: 130,
            filterable: false
        }, {
            title: "Project Name",
            field: "ProjectName",
            attributes: {
                class: "align-center"
            },
            width: 90,
            filterable: false
        }, {
            title: "Turbine",
            field: "Turbine",
            attributes: {
                class: "align-center"
            },
            width: 90,
            filterable: false
        }, {
            title: "Event Type",
            field: "EventType",
            attributes: {
                class: "align-center"
            },
            width: 100,
            filterable: false
        }, {
            title: "Alarm Description",
            field: "AlarmDescription",
            attributes: {
                class: "align-center"
            },
            width: 150,
            filterable: false
        }, {
            title: "Turbine Status",
            field: "TurbineStatus",
            attributes: {
                class: "align-center"
            },
            width: 120,
            filterable: false
        }, {
            title: "Brake Type",
            field: "BrakeType",
            attributes: {
                class: "align-center"
            },
            width: 150,
            filterable: false
        }, {
            title: "Brake Program",
            field: "BrakeProgram",
            width: 120,
            attributes: {
                class: "align-right"
            },
            format: "{0:n2}",
            filterable: false
        }, {
            title: "Alarm Id",
            field: "AlarmId",
            width: 120,
            attributes: {
                class: "align-right"
            },
            format: "{0:n2}",
            filterable: false
        }, {
            title: "Alarm Toggle",
            field: "AlarmToggle",
            width: 120,
            sortable: false,
            template: '# if (AlarmToggle == true ) { #  # } else {# #}#',
            headerAttributes: {
                style: "text-align: center"
            },
            attributes: {
                style: "text-align:center;"
            }
        }, ]
    });
}<commit_msg>remove brakeprogram and alarmid decimal point<commit_after>'use strict';

viewModel.DatabrowserEvent = new Object();
var dbe = viewModel.DatabrowserEvent;

dbe.InitEventGrid = function() {
    dbr.eventrawvis(true);

    var turbine = [];
    if ($("#turbineList").data("kendoMultiSelect").value().indexOf("All Turbine") >= 0) {
        turbine = turbineval;
    } else {
        turbine = $("#turbineList").data("kendoMultiSelect").value();
    }

    var filters = [{
        field: "timestamp",
        operator: "gte",
        value: fa.dateStart
    }, {
        field: "timestamp",
        operator: "lte",
        value: fa.dateEnd
    }, {
        field: "turbine",
        operator: "in",
        value: turbine
    }, ];

    if(fa.project != "") {
        filters.push({
            field: "projectname",
            operator: "eq",
            value: fa.project
        })
    }

    $('#EventGrid').html("");
    $('#EventGrid').kendoGrid({
        dataSource: {
            serverPaging: true,
            serverSorting: true,
            serverFiltering: true,
            filter: filters,
            transport: {
                read: {
                    url: viewModel.appName + "databrowser/geteventlist",
                    type: "POST",
                    data: {},
                    dataType: "json",
                    contentType: "application/json; charset=utf-8"
                },
                parameterMap: function(options) {
                    return JSON.stringify(options);
                }
            },
            pageSize: 10,
            schema: {
                data: function(res) {
                    // app.loading(false);
                    dbr.eventrawvis(false);
                    return res.data.Data
                },
                total: function(res) {
                    if (!app.isFine(res)) {
                        return;
                    }

                    $('#totalturbineEvent').html(kendo.toString(res.data.TotalTurbine, 'n0'));
                    $('#totaldataEvent').html(kendo.toString(res.data.Total, 'n0'));

                    return res.data.Total;
                }
            },
            sort: [{
                field: 'TimeStamp',
                dir: 'asc'
            }, {
                field: 'Turbine',
                dir: 'asc'
            }],
        },
        selectable: "multiple",
        groupable: false,
        sortable: true,
        pageable: {
            pageSize: 10,
            input:true,
        },
        columns: [{
            title: "Time Stamp",
            field: "TimeStamp",
            template: "#= kendo.toString(moment.utc(TimeStamp).format('DD-MMM-YYYY HH:mm:ss'), 'dd-MMM-yyyy HH:mm:ss') #",
            width: 130,
            filterable: false
        }, {
            title: "Project Name",
            field: "ProjectName",
            attributes: {
                class: "align-center"
            },
            width: 90,
            filterable: false
        }, {
            title: "Turbine",
            field: "Turbine",
            attributes: {
                class: "align-center"
            },
            width: 90,
            filterable: false
        }, {
            title: "Event Type",
            field: "EventType",
            attributes: {
                class: "align-center"
            },
            width: 100,
            filterable: false
        }, {
            title: "Alarm Description",
            field: "AlarmDescription",
            attributes: {
                class: "align-center"
            },
            width: 150,
            filterable: false
        }, {
            title: "Turbine Status",
            field: "TurbineStatus",
            attributes: {
                class: "align-center"
            },
            width: 120,
            filterable: false
        }, {
            title: "Brake Type",
            field: "BrakeType",
            attributes: {
                class: "align-center"
            },
            width: 150,
            filterable: false
        }, {
            title: "Brake Program",
            field: "BrakeProgram",
            width: 120,
            attributes: {
                class: "align-right"
            },
            format: "{0}",
            filterable: false
        }, {
            title: "Alarm Id",
            field: "AlarmId",
            width: 120,
            attributes: {
                class: "align-right"
            },
            format: "{0}",
            filterable: false
        }, {
            title: "Alarm Toggle",
            field: "AlarmToggle",
            width: 120,
            sortable: false,
            template: '# if (AlarmToggle == true ) { #  # } else {# #}#',
            headerAttributes: {
                style: "text-align: center"
            },
            attributes: {
                style: "text-align:center;"
            }
        }, ]
    });
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. 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, $, FileError, brackets, unescape, window */

/**
 * Set of utilites for working with files and text content.
 */
define(function (require, exports, module) {
    "use strict";

    require("utils/Global");

    var NativeFileSystem    = require("file/NativeFileSystem").NativeFileSystem,
        NativeFileError     = require("file/NativeFileError"),
        PerfUtils           = require("utils/PerfUtils"),
        Dialogs             = require("widgets/Dialogs"),
        DefaultDialogs      = require("widgets/DefaultDialogs"),
        Strings             = require("strings"),
        StringUtils         = require("utils/StringUtils"),
        Encodings           = NativeFileSystem.Encodings;

    /**
     * Asynchronously reads a file as UTF-8 encoded text.
     * @return {$.Promise} a jQuery promise that will be resolved with the
     *  file's text content plus its timestamp, or rejected with a NativeFileError if
     *  the file can not be read.
     */
    function readAsText(fileEntry) {
        var result = new $.Deferred(),
            reader;

        // Measure performance
        var perfTimerName = PerfUtils.markStart("readAsText:\t" + fileEntry.fullPath);
        result.always(function () {
            PerfUtils.addMeasurement(perfTimerName);
        });

        // Read file
        reader = new NativeFileSystem.FileReader();
        fileEntry.file(function (file) {
            reader.onload = function (event) {
                var text = event.target.result;

                fileEntry.getMetadata(
                    function (metadata) {
                        result.resolve(text, metadata.modificationTime);
                    },
                    function (error) {
                        result.reject(error);
                    }
                );
            };

            reader.onerror = function (event) {
                result.reject(event.target.error);
            };

            reader.readAsText(file, Encodings.UTF8);
        }, function (error) {
            result.reject(error);
        });

        return result.promise();
    }

    /**
     * Asynchronously writes a file as UTF-8 encoded text.
     * @param {!FileEntry} fileEntry
     * @param {!string} text
     * @return {$.Promise} a jQuery promise that will be resolved when
     * file writing completes, or rejected with a NativeFileError.
     */
    function writeText(fileEntry, text) {
        var result = new $.Deferred();

        fileEntry.createWriter(function (fileWriter) {
            fileWriter.onwriteend = function (e) {
                result.resolve();
            };
            fileWriter.onerror = function (err) {
                result.reject(err);
            };

            // TODO (issue #241): NativeFileSystem.BlobBulder
            fileWriter.write(text);
        }, function (error) {
            result.reject(error);
        });

        return result.promise();
    }

    /** @const */
    var LINE_ENDINGS_CRLF = "CRLF";
    /** @const */
    var LINE_ENDINGS_LF = "LF";

    /**
     * Returns the standard line endings for the current platform
     * @return {LINE_ENDINGS_CRLF|LINE_ENDINGS_LF}
     */
    function getPlatformLineEndings() {
        return brackets.platform === "win" ? LINE_ENDINGS_CRLF : LINE_ENDINGS_LF;
    }

    /**
     * Scans the first 1000 chars of the text to determine how it encodes line endings. Returns
     * null if usage is mixed or if no line endings found.
     * @param {!string} text
     * @return {null|LINE_ENDINGS_CRLF|LINE_ENDINGS_LF}
     */
    function sniffLineEndings(text) {
        var subset = text.substr(0, 1000);  // (length is clipped to text.length)
        var hasCRLF = /\r\n/.test(subset);
        var hasLF = /[^\r]\n/.test(subset);

        if ((hasCRLF && hasLF) || (!hasCRLF && !hasLF)) {
            return null;
        } else {
            return hasCRLF ? LINE_ENDINGS_CRLF : LINE_ENDINGS_LF;
        }
    }

    /**
     * Translates any line ending types in the given text to the be the single form specified
     * @param {!string} text
     * @param {null|LINE_ENDINGS_CRLF|LINE_ENDINGS_LF} lineEndings
     * @return {string}
     */
    function translateLineEndings(text, lineEndings) {
        if (lineEndings !== LINE_ENDINGS_CRLF && lineEndings !== LINE_ENDINGS_LF) {
            lineEndings = getPlatformLineEndings();
        }

        var eolStr = (lineEndings === LINE_ENDINGS_CRLF ? "\r\n" : "\n");
        var findAnyEol = /\r\n|\r|\n/g;

        return text.replace(findAnyEol, eolStr);
    }

    function getFileErrorString(name) {
        // There are a few error codes that we have specific error messages for. The rest are
        // displayed with a generic "(error N)" message.
        var result;

        if (name === NativeFileError.NOT_FOUND_ERR) {
            result = Strings.NOT_FOUND_ERR;
        } else if (name === NativeFileError.NOT_READABLE_ERR) {
            result = Strings.NOT_READABLE_ERR;
        } else if (name === NativeFileError.NO_MODIFICATION_ALLOWED_ERR) {
            result = Strings.NO_MODIFICATION_ALLOWED_ERR_FILE;
        } else {
            result = StringUtils.format(Strings.GENERIC_ERROR, name);
        }

        return result;
    }

    function showFileOpenError(name, path) {
        return Dialogs.showModalDialog(
            DefaultDialogs.DIALOG_ID_ERROR,
            Strings.ERROR_OPENING_FILE_TITLE,
            StringUtils.format(
                Strings.ERROR_OPENING_FILE,
                StringUtils.breakableUrl(path),
                getFileErrorString(name)
            )
        );
    }

    /**
     * Convert a URI path to a native path.
     * On both platforms, this unescapes the URI
     * On windows, URI paths start with a "/", but have a drive letter ("C:"). In this
     * case, remove the initial "/".
     * @param {!string} path
     * @return {string}
     */
    function convertToNativePath(path) {
        path = unescape(path);
        if (path.indexOf(":") !== -1 && path[0] === "/") {
            return path.substr(1);
        }

        return path;
    }

    /**
     * Convert a Windows-native path to use Unix style slashes.
     * On Windows, this converts "C:\foo\bar\baz.txt" to "C:/foo/bar/baz.txt".
     * On Mac, this does nothing, since Mac paths are already in Unix syntax.
     * (Note that this does not add an initial forward-slash. Internally, our
     * APIs generally use the "C:/foo/bar/baz.txt" style for "native" paths.)
     * @param {string} path A native-style path.
     * @return {string} A Unix-style path.
     */
    function convertWindowsPathToUnixPath(path) {
        if (brackets.platform === "win") {
            path = path.replace(/\\/g, "/");
        }
        return path;
    }

    /**
     * Canonicalizes a folder path to not include a trailing slash.
     * @param {string} path
     * @return {string}
     */
    function canonicalizeFolderPath(path) {
        if (path.length > 0 && path[path.length - 1] === "/") {
            return path.slice(0, -1);
        } else {
            return path;
        }
    }

    /**
     * Returns a native absolute path to the 'brackets' source directory.
     * Note that this only works when run in brackets/src/index.html, so it does
     * not work for unit tests (which is run from brackets/test/SpecRunner.html)
     * @return {string}
     */
    function getNativeBracketsDirectoryPath() {
        var pathname = decodeURI(window.location.pathname);
        var directory = pathname.substr(0, pathname.lastIndexOf("/"));
        return convertToNativePath(directory);
    }

    /**
     * Given the module object passed to JS module define function,
     * convert the path to a native absolute path.
     * Returns a native absolute path to the module folder.
     * @return {string}
     */
    function getNativeModuleDirectoryPath(module) {
        var path;

        if (module && module.uri) {
            path = decodeURI(module.uri);

            // Remove module name and trailing slash from path.
            path = path.substr(0, path.lastIndexOf("/"));
        }
        return path;
    }

    /**
     * Checks wheter a path is affected by a rename operation.
     * A path is affected if the object being renamed is a file and the given path refers
     * to that file or if the object being renamed is a directory and a prefix of the path.
     * Always checking for prefixes can create conflicts:
     * renaming file "foo" should not affect file "foobar/baz" even though "foo" is a prefix of "foobar".
     * @param {!string} path The path potentially affected
     * @param {!string} oldName An object's name before renaming
     * @param {!string} newName An object's name after renaming
     * @param {?boolean} isFolder Whether the renamed object is a folder or not
     */
    function isAffectedWhenRenaming(path, oldName, newName, isFolder) {
        isFolder = isFolder || oldName.slice(-1) === "/";
        return (isFolder && path.indexOf(oldName) === 0) || (!isFolder && path === oldName);
    }

    /**
     * Update a file entry path after a file/folder name change.
     * @param {FileEntry} entry The FileEntry or DirectoryEntry to update
     * @param {string} oldName The full path of the old name
     * @param {string} newName The full path of the new name
     * @return {boolean} Returns true if the file entry was updated
     */
    function updateFileEntryPath(entry, oldName, newName, isFolder) {
        if (isAffectedWhenRenaming(entry.fullPath, oldName, newName, isFolder)) {
            var oldFullPath = entry.fullPath;
            var fullPath = oldFullPath.replace(oldName, newName);
            entry.fullPath = fullPath;

            // TODO: Should this be a method on Entry instead?
            entry.name = null; // default if extraction fails
            if (fullPath) {
                var pathParts = fullPath.split("/");

                // Extract name from the end of the fullPath (account for trailing slash(es))
                while (!entry.name && pathParts.length) {
                    entry.name = pathParts.pop();
                }
            }

            return true;
        }

        return false;
    }

    /**
     * Returns the file extension for a file name
     * @param {string} fileName file name with extension or just a file extension
     * @return {string} File extension if found, otherwise return the original file name
     */
    function _getFileExtension(fileName) {
        var i = fileName.lastIndexOf("."),
            ext = (i === -1 || i >= fileName.length - 1) ? fileName : fileName.substr(i + 1);

        return ext;
    }

    /** @const - hard-coded for now, but may want to make these preferences */
    var _staticHtmlFileExts = ["htm", "html"],
        _serverHtmlFileExts = ["php", "php3", "php4", "php5", "phtm", "phtml", "cfm", "cfml", "asp", "aspx", "jsp", "jspx", "shtm", "shtml"];

    /**
     * Determine if file extension is a static html file extension.
     * @param {string} fileExt file name with extension or just a file extension
     * @return {boolean} Returns true if fileExt is in the list
     */
    function isStaticHtmlFileExt(fileExt) {
        if (!fileExt) {
            return false;
        }

        return (_staticHtmlFileExts.indexOf(_getFileExtension(fileExt).toLowerCase()) !== -1);
    }

    /**
     * Determine if file extension is a server html file extension.
     * @param {string} fileExt file name with extension or just a file extension
     * @return {boolean} Returns true if fileExt is in the list
     */
    function isServerHtmlFileExt(fileExt) {
        if (!fileExt) {
            return false;
        }

        return (_serverHtmlFileExts.indexOf(_getFileExtension(fileExt).toLowerCase()) !== -1);
    }

    /**
     * Get the parent directory of a file. If a directory is passed in the directory is returned.
     * @param {string} fullPath full path to a file or directory
     * @return {string} Returns the path to the parent directory of a file or the path of a directory
     */
    function getDirectoryPath(fullPath) {
        return fullPath.substr(0, fullPath.lastIndexOf("/") + 1);
    }

    /**
     * Get the base name of a file or a directory.
     * @param {string} fullPath full path to a file or directory
     * @return {string} Returns the base name of a file or the name of a
     * directory
     */
    function getBaseName(fullPath) {
        fullPath = canonicalizeFolderPath(fullPath);
        return fullPath.substr(fullPath.lastIndexOf("/") + 1);
    }

    /**
     * Get the filename extension.
     *
     * @param {string} fullPath full path to a file or directory
     * @return {string} Returns the extension of a filename or empty string if
     * the argument is a directory or a filename with no extension
     */
    function getFilenameExtension(fullPath) {
        var baseName = getBaseName(fullPath),
            idx      = baseName.lastIndexOf(".");

        if (idx === -1) {
            return "";
        }

        return baseName.substr(idx);
    }

    /**
     * @private
     * Get the file name without the extension.
     * @param {string} filename File name of a file or directory
     * @return {string} Returns the file name without the extension
     */
    function _getFilenameWithoutExtension(filename) {
        var extension = getFilenameExtension(filename);
        return extension ? filename.replace(new RegExp(extension + "$"), "") : filename;
    }

    /**
     * Compares 2 filenames in lowercases. In Windows it compares the names without the
     * extension first and then the extensions to fix issue #4409
     * @param {string} filename1
     * @param {string} filename2
     * @param {boolean} extFirst If true it compares the extensions first and then the file names.
     * @return {number} The result of the local compare function
     */
    function compareFilenames(filename1, filename2, extFirst) {
        var ext1   = getFilenameExtension(filename1),
            ext2   = getFilenameExtension(filename2),
            cmpExt = ext1.toLocaleLowerCase().localeCompare(ext2.toLocaleLowerCase()),
            cmpNames;

        if (brackets.platform === "win") {
            filename1 = _getFilenameWithoutExtension(filename1);
            filename2 = _getFilenameWithoutExtension(filename2);
        }
        cmpNames = filename1.toLocaleLowerCase().localeCompare(filename2.toLocaleLowerCase(), undefined, {numeric: true});

        return extFirst ? (cmpExt || cmpNames) : (cmpNames || cmpExt);
    }

    // Define public API
    exports.LINE_ENDINGS_CRLF              = LINE_ENDINGS_CRLF;
    exports.LINE_ENDINGS_LF                = LINE_ENDINGS_LF;
    exports.getPlatformLineEndings         = getPlatformLineEndings;
    exports.sniffLineEndings               = sniffLineEndings;
    exports.translateLineEndings           = translateLineEndings;
    exports.showFileOpenError              = showFileOpenError;
    exports.getFileErrorString             = getFileErrorString;
    exports.readAsText                     = readAsText;
    exports.writeText                      = writeText;
    exports.convertToNativePath            = convertToNativePath;
    exports.convertWindowsPathToUnixPath   = convertWindowsPathToUnixPath;
    exports.getNativeBracketsDirectoryPath = getNativeBracketsDirectoryPath;
    exports.getNativeModuleDirectoryPath   = getNativeModuleDirectoryPath;
    exports.canonicalizeFolderPath         = canonicalizeFolderPath;
    exports.isAffectedWhenRenaming         = isAffectedWhenRenaming;
    exports.updateFileEntryPath            = updateFileEntryPath;
    exports.isStaticHtmlFileExt            = isStaticHtmlFileExt;
    exports.isServerHtmlFileExt            = isServerHtmlFileExt;
    exports.getDirectoryPath               = getDirectoryPath;
    exports.getBaseName                    = getBaseName;
    exports.getFilenameExtension           = getFilenameExtension;
    exports.compareFilenames               = compareFilenames;
});
<commit_msg>Fix for extensions compare<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. 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, $, FileError, brackets, unescape, window */

/**
 * Set of utilites for working with files and text content.
 */
define(function (require, exports, module) {
    "use strict";

    require("utils/Global");

    var NativeFileSystem    = require("file/NativeFileSystem").NativeFileSystem,
        NativeFileError     = require("file/NativeFileError"),
        PerfUtils           = require("utils/PerfUtils"),
        Dialogs             = require("widgets/Dialogs"),
        DefaultDialogs      = require("widgets/DefaultDialogs"),
        Strings             = require("strings"),
        StringUtils         = require("utils/StringUtils"),
        Encodings           = NativeFileSystem.Encodings;

    /**
     * Asynchronously reads a file as UTF-8 encoded text.
     * @return {$.Promise} a jQuery promise that will be resolved with the
     *  file's text content plus its timestamp, or rejected with a NativeFileError if
     *  the file can not be read.
     */
    function readAsText(fileEntry) {
        var result = new $.Deferred(),
            reader;

        // Measure performance
        var perfTimerName = PerfUtils.markStart("readAsText:\t" + fileEntry.fullPath);
        result.always(function () {
            PerfUtils.addMeasurement(perfTimerName);
        });

        // Read file
        reader = new NativeFileSystem.FileReader();
        fileEntry.file(function (file) {
            reader.onload = function (event) {
                var text = event.target.result;

                fileEntry.getMetadata(
                    function (metadata) {
                        result.resolve(text, metadata.modificationTime);
                    },
                    function (error) {
                        result.reject(error);
                    }
                );
            };

            reader.onerror = function (event) {
                result.reject(event.target.error);
            };

            reader.readAsText(file, Encodings.UTF8);
        }, function (error) {
            result.reject(error);
        });

        return result.promise();
    }

    /**
     * Asynchronously writes a file as UTF-8 encoded text.
     * @param {!FileEntry} fileEntry
     * @param {!string} text
     * @return {$.Promise} a jQuery promise that will be resolved when
     * file writing completes, or rejected with a NativeFileError.
     */
    function writeText(fileEntry, text) {
        var result = new $.Deferred();

        fileEntry.createWriter(function (fileWriter) {
            fileWriter.onwriteend = function (e) {
                result.resolve();
            };
            fileWriter.onerror = function (err) {
                result.reject(err);
            };

            // TODO (issue #241): NativeFileSystem.BlobBulder
            fileWriter.write(text);
        }, function (error) {
            result.reject(error);
        });

        return result.promise();
    }

    /** @const */
    var LINE_ENDINGS_CRLF = "CRLF";
    /** @const */
    var LINE_ENDINGS_LF = "LF";

    /**
     * Returns the standard line endings for the current platform
     * @return {LINE_ENDINGS_CRLF|LINE_ENDINGS_LF}
     */
    function getPlatformLineEndings() {
        return brackets.platform === "win" ? LINE_ENDINGS_CRLF : LINE_ENDINGS_LF;
    }

    /**
     * Scans the first 1000 chars of the text to determine how it encodes line endings. Returns
     * null if usage is mixed or if no line endings found.
     * @param {!string} text
     * @return {null|LINE_ENDINGS_CRLF|LINE_ENDINGS_LF}
     */
    function sniffLineEndings(text) {
        var subset = text.substr(0, 1000);  // (length is clipped to text.length)
        var hasCRLF = /\r\n/.test(subset);
        var hasLF = /[^\r]\n/.test(subset);

        if ((hasCRLF && hasLF) || (!hasCRLF && !hasLF)) {
            return null;
        } else {
            return hasCRLF ? LINE_ENDINGS_CRLF : LINE_ENDINGS_LF;
        }
    }

    /**
     * Translates any line ending types in the given text to the be the single form specified
     * @param {!string} text
     * @param {null|LINE_ENDINGS_CRLF|LINE_ENDINGS_LF} lineEndings
     * @return {string}
     */
    function translateLineEndings(text, lineEndings) {
        if (lineEndings !== LINE_ENDINGS_CRLF && lineEndings !== LINE_ENDINGS_LF) {
            lineEndings = getPlatformLineEndings();
        }

        var eolStr = (lineEndings === LINE_ENDINGS_CRLF ? "\r\n" : "\n");
        var findAnyEol = /\r\n|\r|\n/g;

        return text.replace(findAnyEol, eolStr);
    }

    function getFileErrorString(name) {
        // There are a few error codes that we have specific error messages for. The rest are
        // displayed with a generic "(error N)" message.
        var result;

        if (name === NativeFileError.NOT_FOUND_ERR) {
            result = Strings.NOT_FOUND_ERR;
        } else if (name === NativeFileError.NOT_READABLE_ERR) {
            result = Strings.NOT_READABLE_ERR;
        } else if (name === NativeFileError.NO_MODIFICATION_ALLOWED_ERR) {
            result = Strings.NO_MODIFICATION_ALLOWED_ERR_FILE;
        } else {
            result = StringUtils.format(Strings.GENERIC_ERROR, name);
        }

        return result;
    }

    function showFileOpenError(name, path) {
        return Dialogs.showModalDialog(
            DefaultDialogs.DIALOG_ID_ERROR,
            Strings.ERROR_OPENING_FILE_TITLE,
            StringUtils.format(
                Strings.ERROR_OPENING_FILE,
                StringUtils.breakableUrl(path),
                getFileErrorString(name)
            )
        );
    }

    /**
     * Convert a URI path to a native path.
     * On both platforms, this unescapes the URI
     * On windows, URI paths start with a "/", but have a drive letter ("C:"). In this
     * case, remove the initial "/".
     * @param {!string} path
     * @return {string}
     */
    function convertToNativePath(path) {
        path = unescape(path);
        if (path.indexOf(":") !== -1 && path[0] === "/") {
            return path.substr(1);
        }

        return path;
    }

    /**
     * Convert a Windows-native path to use Unix style slashes.
     * On Windows, this converts "C:\foo\bar\baz.txt" to "C:/foo/bar/baz.txt".
     * On Mac, this does nothing, since Mac paths are already in Unix syntax.
     * (Note that this does not add an initial forward-slash. Internally, our
     * APIs generally use the "C:/foo/bar/baz.txt" style for "native" paths.)
     * @param {string} path A native-style path.
     * @return {string} A Unix-style path.
     */
    function convertWindowsPathToUnixPath(path) {
        if (brackets.platform === "win") {
            path = path.replace(/\\/g, "/");
        }
        return path;
    }

    /**
     * Canonicalizes a folder path to not include a trailing slash.
     * @param {string} path
     * @return {string}
     */
    function canonicalizeFolderPath(path) {
        if (path.length > 0 && path[path.length - 1] === "/") {
            return path.slice(0, -1);
        } else {
            return path;
        }
    }

    /**
     * Returns a native absolute path to the 'brackets' source directory.
     * Note that this only works when run in brackets/src/index.html, so it does
     * not work for unit tests (which is run from brackets/test/SpecRunner.html)
     * @return {string}
     */
    function getNativeBracketsDirectoryPath() {
        var pathname = decodeURI(window.location.pathname);
        var directory = pathname.substr(0, pathname.lastIndexOf("/"));
        return convertToNativePath(directory);
    }

    /**
     * Given the module object passed to JS module define function,
     * convert the path to a native absolute path.
     * Returns a native absolute path to the module folder.
     * @return {string}
     */
    function getNativeModuleDirectoryPath(module) {
        var path;

        if (module && module.uri) {
            path = decodeURI(module.uri);

            // Remove module name and trailing slash from path.
            path = path.substr(0, path.lastIndexOf("/"));
        }
        return path;
    }

    /**
     * Checks wheter a path is affected by a rename operation.
     * A path is affected if the object being renamed is a file and the given path refers
     * to that file or if the object being renamed is a directory and a prefix of the path.
     * Always checking for prefixes can create conflicts:
     * renaming file "foo" should not affect file "foobar/baz" even though "foo" is a prefix of "foobar".
     * @param {!string} path The path potentially affected
     * @param {!string} oldName An object's name before renaming
     * @param {!string} newName An object's name after renaming
     * @param {?boolean} isFolder Whether the renamed object is a folder or not
     */
    function isAffectedWhenRenaming(path, oldName, newName, isFolder) {
        isFolder = isFolder || oldName.slice(-1) === "/";
        return (isFolder && path.indexOf(oldName) === 0) || (!isFolder && path === oldName);
    }

    /**
     * Update a file entry path after a file/folder name change.
     * @param {FileEntry} entry The FileEntry or DirectoryEntry to update
     * @param {string} oldName The full path of the old name
     * @param {string} newName The full path of the new name
     * @return {boolean} Returns true if the file entry was updated
     */
    function updateFileEntryPath(entry, oldName, newName, isFolder) {
        if (isAffectedWhenRenaming(entry.fullPath, oldName, newName, isFolder)) {
            var oldFullPath = entry.fullPath;
            var fullPath = oldFullPath.replace(oldName, newName);
            entry.fullPath = fullPath;

            // TODO: Should this be a method on Entry instead?
            entry.name = null; // default if extraction fails
            if (fullPath) {
                var pathParts = fullPath.split("/");

                // Extract name from the end of the fullPath (account for trailing slash(es))
                while (!entry.name && pathParts.length) {
                    entry.name = pathParts.pop();
                }
            }

            return true;
        }

        return false;
    }

    /**
     * Returns the file extension for a file name
     * @param {string} fileName file name with extension or just a file extension
     * @return {string} File extension if found, otherwise return the original file name
     */
    function _getFileExtension(fileName) {
        var i = fileName.lastIndexOf("."),
            ext = (i === -1 || i >= fileName.length - 1) ? fileName : fileName.substr(i + 1);

        return ext;
    }

    /** @const - hard-coded for now, but may want to make these preferences */
    var _staticHtmlFileExts = ["htm", "html"],
        _serverHtmlFileExts = ["php", "php3", "php4", "php5", "phtm", "phtml", "cfm", "cfml", "asp", "aspx", "jsp", "jspx", "shtm", "shtml"];

    /**
     * Determine if file extension is a static html file extension.
     * @param {string} fileExt file name with extension or just a file extension
     * @return {boolean} Returns true if fileExt is in the list
     */
    function isStaticHtmlFileExt(fileExt) {
        if (!fileExt) {
            return false;
        }

        return (_staticHtmlFileExts.indexOf(_getFileExtension(fileExt).toLowerCase()) !== -1);
    }

    /**
     * Determine if file extension is a server html file extension.
     * @param {string} fileExt file name with extension or just a file extension
     * @return {boolean} Returns true if fileExt is in the list
     */
    function isServerHtmlFileExt(fileExt) {
        if (!fileExt) {
            return false;
        }

        return (_serverHtmlFileExts.indexOf(_getFileExtension(fileExt).toLowerCase()) !== -1);
    }

    /**
     * Get the parent directory of a file. If a directory is passed in the directory is returned.
     * @param {string} fullPath full path to a file or directory
     * @return {string} Returns the path to the parent directory of a file or the path of a directory
     */
    function getDirectoryPath(fullPath) {
        return fullPath.substr(0, fullPath.lastIndexOf("/") + 1);
    }

    /**
     * Get the base name of a file or a directory.
     * @param {string} fullPath full path to a file or directory
     * @return {string} Returns the base name of a file or the name of a
     * directory
     */
    function getBaseName(fullPath) {
        fullPath = canonicalizeFolderPath(fullPath);
        return fullPath.substr(fullPath.lastIndexOf("/") + 1);
    }

    /**
     * Get the filename extension.
     *
     * @param {string} fullPath full path to a file or directory
     * @return {string} Returns the extension of a filename or empty string if
     * the argument is a directory or a filename with no extension
     */
    function getFilenameExtension(fullPath) {
        var baseName = getBaseName(fullPath),
            idx      = baseName.lastIndexOf(".");

        if (idx === -1) {
            return "";
        }

        return baseName.substr(idx);
    }

    /**
     * @private
     * Get the file name without the extension.
     * @param {string} filename File name of a file or directory
     * @return {string} Returns the file name without the extension
     */
    function _getFilenameWithoutExtension(filename) {
        var extension = getFilenameExtension(filename);
        return extension ? filename.replace(new RegExp(extension + "$"), "") : filename;
    }

    /**
     * Compares 2 filenames in lowercases. In Windows it compares the names without the
     * extension first and then the extensions to fix issue #4409
     * @param {string} filename1
     * @param {string} filename2
     * @param {boolean} extFirst If true it compares the extensions first and then the file names.
     * @return {number} The result of the local compare function
     */
    function compareFilenames(filename1, filename2, extFirst) {
        var ext1   = getFilenameExtension(filename1),
            ext2   = getFilenameExtension(filename2),
            cmpExt = ext1.toLocaleLowerCase().localeCompare(ext2.toLocaleLowerCase(), undefined, {numeric: true}),
            cmpNames;

        if (brackets.platform === "win") {
            filename1 = _getFilenameWithoutExtension(filename1);
            filename2 = _getFilenameWithoutExtension(filename2);
        }
        cmpNames = filename1.toLocaleLowerCase().localeCompare(filename2.toLocaleLowerCase(), undefined, {numeric: true});

        return extFirst ? (cmpExt || cmpNames) : (cmpNames || cmpExt);
    }

    // Define public API
    exports.LINE_ENDINGS_CRLF              = LINE_ENDINGS_CRLF;
    exports.LINE_ENDINGS_LF                = LINE_ENDINGS_LF;
    exports.getPlatformLineEndings         = getPlatformLineEndings;
    exports.sniffLineEndings               = sniffLineEndings;
    exports.translateLineEndings           = translateLineEndings;
    exports.showFileOpenError              = showFileOpenError;
    exports.getFileErrorString             = getFileErrorString;
    exports.readAsText                     = readAsText;
    exports.writeText                      = writeText;
    exports.convertToNativePath            = convertToNativePath;
    exports.convertWindowsPathToUnixPath   = convertWindowsPathToUnixPath;
    exports.getNativeBracketsDirectoryPath = getNativeBracketsDirectoryPath;
    exports.getNativeModuleDirectoryPath   = getNativeModuleDirectoryPath;
    exports.canonicalizeFolderPath         = canonicalizeFolderPath;
    exports.isAffectedWhenRenaming         = isAffectedWhenRenaming;
    exports.updateFileEntryPath            = updateFileEntryPath;
    exports.isStaticHtmlFileExt            = isStaticHtmlFileExt;
    exports.isServerHtmlFileExt            = isServerHtmlFileExt;
    exports.getDirectoryPath               = getDirectoryPath;
    exports.getBaseName                    = getBaseName;
    exports.getFilenameExtension           = getFilenameExtension;
    exports.compareFilenames               = compareFilenames;
});
<|endoftext|>