<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Behavior for "fixed" headers and footers - be sure to also include the item 'Browser specific workarounds for "fixed" headers and footers' when supporting Android 2.x or iOS 5
//>>label: Toolbars: Fixed
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.fixedToolbar.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "../jquery.mobile.core", "../jquery.mobile.navigation", "./page", "./page.sections", "../jquery.mobile.zoom" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

	$.widget( "mobile.fixedtoolbar", $.mobile.widget, {
		options: {
			visibleOnPageShow: true,
			disablePageZoom: true,
			transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown)
			fullscreen: false,
			tapToggle: true,
			tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-popup, .ui-panel, .ui-panel-dismiss-open",
			hideDuringFocus: "input, textarea, select",
			updatePagePadding: true,
			trackPersistentToolbars: true,

			// Browser detection! Weeee, here we go...
			// Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately.
			// Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience.
			// Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window
			// The following function serves to rule out some popular browsers with known fixed-positioning issues
			// This is a plugin option like any other, so feel free to improve or overwrite it
			supportBlacklist: function() {
				return !$.support.fixedPosition;
			},
			initSelector: ":jqmData(position='fixed')"
		},

		_create: function() {

			var self = this,
				o = self.options,
				$el = self.element,
				tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer",
				$page = $el.closest( ".ui-page" );

			// Feature detecting support for
			if ( o.supportBlacklist() ) {
				self.destroy();
				return;
			}

			$el.addClass( "ui-"+ tbtype +"-fixed" );

			// "fullscreen" overlay positioning
			if ( o.fullscreen ) {
				$el.addClass( "ui-"+ tbtype +"-fullscreen" );
				$page.addClass( "ui-page-" + tbtype + "-fullscreen" );
			}
			// If not fullscreen, add class to page to set top or bottom padding
			else{
				$page.addClass( "ui-page-" + tbtype + "-fixed" );
			}

			$.extend( this, {
				_thisPage: null
			});

			self._addTransitionClass();
			self._bindPageEvents();
			self._bindToggleHandlers();
		},

		_addTransitionClass: function() {
			var tclass = this.options.transition;

			if ( tclass && tclass !== "none" ) {
				// use appropriate slide for header or footer
				if ( tclass === "slide" ) {
					tclass = this.element.hasClass( "ui-header" ) ? "slidedown" : "slideup";
				}

				this.element.addClass( tclass );
			}
		},

		_bindPageEvents: function() {
			this._thisPage = this.element.closest( ".ui-page" );
			//page event bindings
			// Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up
			// This method is meant to disable zoom while a fixed-positioned toolbar page is visible
			this._on( this._thisPage, {
				"pagebeforeshow": "_handlePageBeforeShow",
				"webkitAnimationStart":"_handleAnimationStart",
				"animationstart":"_handleAnimationStart",
				"updatelayout": "_handleAnimationStart",
				"pageshow": "_handlePageShow",
				"pagebeforehide": "_handlePageBeforeHide"
			});
		},

		_handlePageBeforeShow: function() {
			var o = this.options;
			if ( o.disablePageZoom ) {
				$.mobile.zoom.disable( true );
			}
			if ( !o.visibleOnPageShow ) {
				this.hide( true );
			}
		},

		_handleAnimationStart: function() {
			if ( this.options.updatePagePadding ) {
				this.updatePagePadding( this._thisPage );
			}
		},

		_handlePageShow: function() {
			this.updatePagePadding( this._thisPage );
			if ( this.options.updatePagePadding ) {
				this._on( $.mobile.window, { "throttledresize": "updatePagePadding" } );
			}
		},

		_handlePageBeforeHide: function( e, ui ) {
			var o = this.options;

			if ( o.disablePageZoom ) {
				$.mobile.zoom.enable( true );
			}
			if ( o.updatePagePadding ) {
				this._off( $.mobile.window, "throttledresize" );
			}

			if ( o.trackPersistentToolbars ) {
				var thisFooter = $( ".ui-footer-fixed:jqmData(id)", this._thisPage ),
					thisHeader = $( ".ui-header-fixed:jqmData(id)", this._thisPage ),
					nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(),
					nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $();

				if ( nextFooter.length || nextHeader.length ) {

					nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer );

					ui.nextPage.one( "pageshow", function() {
						nextHeader.prependTo( this );
						nextFooter.appendTo( this );
					});
				}
			}
		},

		_visible: true,

		// This will set the content element's top or bottom padding equal to the toolbar's height
		updatePagePadding: function( tbPage ) {
			var $el = this.element,
				header = $el.hasClass( "ui-header" ),
				pos = parseFloat( $el.css( header ? "top" : "bottom" ) );

			// This behavior only applies to "fixed", not "fullscreen"
			if ( this.options.fullscreen ) { return; }

			tbPage = tbPage || this._thisPage || $el.closest( ".ui-page" );
			$( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos );
		},

		_useTransition: function( notransition ) {
			var $win = $.mobile.window,
				$el = this.element,
				scroll = $win.scrollTop(),
				elHeight = $el.height(),
				pHeight = $el.closest( ".ui-page" ).height(),
				viewportHeight = $.mobile.getScreenHeight(),
				tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer";

			return !notransition &&
				( this.options.transition && this.options.transition !== "none" &&
				(
					( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) ||
					( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight )
				) || this.options.fullscreen
				);
		},

		show: function( notransition ) {
			var hideClass = "ui-fixed-hidden",
				$el = this.element;

			if ( this._useTransition( notransition ) ) {
				$el
					.removeClass( "out " + hideClass )
					.addClass( "in" )
					.animationComplete(function () {
						$el.removeClass('in');
					});
			}
			else {
				$el.removeClass( hideClass );
			}
			this._visible = true;
		},

		hide: function( notransition ) {
			var hideClass = "ui-fixed-hidden",
				$el = this.element,
				// if it's a slide transition, our new transitions need the reverse class as well to slide outward
				outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" );

			if( this._useTransition( notransition ) ) {
				$el
					.addClass( outclass )
					.removeClass( "in" )
					.animationComplete(function() {
						$el.addClass( hideClass ).removeClass( outclass );
					});
			}
			else {
				$el.addClass( hideClass ).removeClass( outclass );
			}
			this._visible = false;
		},

		toggle: function() {
			this[ this._visible ? "hide" : "show" ]();
		},

		_bindToggleHandlers: function() {
			var self = this,
				o = self.options,
				$el = self.element,
				delayShow, delayHide,
				isVisible = true;

			// tap toggle
			$el.closest( ".ui-page" )
				.bind( "vclick", function( e ) {
					if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) {
						self.toggle();
					}
				})
				.bind( "focusin focusout", function( e ) {
					//this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which
					//positions fixed toolbars in the middle of the screen on pop if the input is near the top or
					//bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment
					//and issue #4113 Header and footer change their position after keyboard popup - iOS
					//and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment
					if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) {
						//Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system
						//controls causes fixed position, tap-toggle false Header to reveal itself
						// isVisible instead of self._visible because the focusin and focusout events fire twice at the same time
						// Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed
						// by a focusout when a native selects opens and the other way around when it closes.
						if ( e.type === "focusout" && !isVisible ) {
							isVisible = true;
							//wait for the stack to unwind and see if we have jumped to another input
							clearTimeout( delayHide );
							delayShow = setTimeout( function() {
								self.show();
							}, 0 );
						} else if ( e.type === "focusin" && !!isVisible ) {
							//if we have jumped to another input clear the time out to cancel the show.
							clearTimeout( delayShow );
							isVisible = false;
							delayHide = setTimeout( function() {
								self.hide();
							}, 0 );
						}
					}
				});
		},

		_destroy: function() {
			var $el = this.element,
				header = $el.hasClass( "ui-header" );

			$el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" );
			$el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" );
			$el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" );
		}

	});

	//auto self-init widgets
	$.mobile.document
		.bind( "pagecreate create", function( e ) {

			// DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element.
			// This line ensures it still works, but we recommend moving the attribute to the toolbars themselves.
			if ( $( e.target ).jqmData( "fullscreen" ) ) {
				$( $.mobile.fixedtoolbar.prototype.options.initSelector, e.target ).not( ":jqmData(fullscreen)" ).jqmData( "fullscreen", true );
			}

			$.mobile.fixedtoolbar.prototype.enhanceWithin( e.target );
		});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>the first argument of updatePagePadding is expected to be a page, but when it is called from the throttledResize binding, it ends up as an event object, and the padding was being set on that instead of the page. This adds a check to ensure the arg is a page before setting its padding. This is a fix for #5619<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Behavior for "fixed" headers and footers - be sure to also include the item 'Browser specific workarounds for "fixed" headers and footers' when supporting Android 2.x or iOS 5
//>>label: Toolbars: Fixed
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.fixedToolbar.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "../jquery.mobile.core", "../jquery.mobile.navigation", "./page", "./page.sections", "../jquery.mobile.zoom" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

	$.widget( "mobile.fixedtoolbar", $.mobile.widget, {
		options: {
			visibleOnPageShow: true,
			disablePageZoom: true,
			transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown)
			fullscreen: false,
			tapToggle: true,
			tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-popup, .ui-panel, .ui-panel-dismiss-open",
			hideDuringFocus: "input, textarea, select",
			updatePagePadding: true,
			trackPersistentToolbars: true,

			// Browser detection! Weeee, here we go...
			// Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately.
			// Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience.
			// Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window
			// The following function serves to rule out some popular browsers with known fixed-positioning issues
			// This is a plugin option like any other, so feel free to improve or overwrite it
			supportBlacklist: function() {
				return !$.support.fixedPosition;
			},
			initSelector: ":jqmData(position='fixed')"
		},

		_create: function() {

			var self = this,
				o = self.options,
				$el = self.element,
				tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer",
				$page = $el.closest( ".ui-page" );

			// Feature detecting support for
			if ( o.supportBlacklist() ) {
				self.destroy();
				return;
			}

			$el.addClass( "ui-"+ tbtype +"-fixed" );

			// "fullscreen" overlay positioning
			if ( o.fullscreen ) {
				$el.addClass( "ui-"+ tbtype +"-fullscreen" );
				$page.addClass( "ui-page-" + tbtype + "-fullscreen" );
			}
			// If not fullscreen, add class to page to set top or bottom padding
			else{
				$page.addClass( "ui-page-" + tbtype + "-fixed" );
			}

			$.extend( this, {
				_thisPage: null
			});

			self._addTransitionClass();
			self._bindPageEvents();
			self._bindToggleHandlers();
		},

		_addTransitionClass: function() {
			var tclass = this.options.transition;

			if ( tclass && tclass !== "none" ) {
				// use appropriate slide for header or footer
				if ( tclass === "slide" ) {
					tclass = this.element.hasClass( "ui-header" ) ? "slidedown" : "slideup";
				}

				this.element.addClass( tclass );
			}
		},

		_bindPageEvents: function() {
			this._thisPage = this.element.closest( ".ui-page" );
			//page event bindings
			// Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up
			// This method is meant to disable zoom while a fixed-positioned toolbar page is visible
			this._on( this._thisPage, {
				"pagebeforeshow": "_handlePageBeforeShow",
				"webkitAnimationStart":"_handleAnimationStart",
				"animationstart":"_handleAnimationStart",
				"updatelayout": "_handleAnimationStart",
				"pageshow": "_handlePageShow",
				"pagebeforehide": "_handlePageBeforeHide"
			});
		},

		_handlePageBeforeShow: function() {
			var o = this.options;
			if ( o.disablePageZoom ) {
				$.mobile.zoom.disable( true );
			}
			if ( !o.visibleOnPageShow ) {
				this.hide( true );
			}
		},

		_handleAnimationStart: function() {
			if ( this.options.updatePagePadding ) {
				this.updatePagePadding( this._thisPage );
			}
		},

		_handlePageShow: function() {
			this.updatePagePadding( this._thisPage );
			if ( this.options.updatePagePadding ) {
				this._on( $.mobile.window, { "throttledresize": "updatePagePadding" } );
			}
		},

		_handlePageBeforeHide: function( e, ui ) {
			var o = this.options;

			if ( o.disablePageZoom ) {
				$.mobile.zoom.enable( true );
			}
			if ( o.updatePagePadding ) {
				this._off( $.mobile.window, "throttledresize" );
			}

			if ( o.trackPersistentToolbars ) {
				var thisFooter = $( ".ui-footer-fixed:jqmData(id)", this._thisPage ),
					thisHeader = $( ".ui-header-fixed:jqmData(id)", this._thisPage ),
					nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(),
					nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $();

				if ( nextFooter.length || nextHeader.length ) {

					nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer );

					ui.nextPage.one( "pageshow", function() {
						nextHeader.prependTo( this );
						nextFooter.appendTo( this );
					});
				}
			}
		},

		_visible: true,

		// This will set the content element's top or bottom padding equal to the toolbar's height
		updatePagePadding: function( tbPage ) {
			var $el = this.element,
				header = $el.hasClass( "ui-header" ),
				pos = parseFloat( $el.css( header ? "top" : "bottom" ) );

			// This behavior only applies to "fixed", not "fullscreen"
			if ( this.options.fullscreen ) { return; }

			// tbPage argument can be a Page object or an event, if coming from throttled resize.
			tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this._thisPage || $el.closest( ".ui-page" );
			$( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos );
		},

		_useTransition: function( notransition ) {
			var $win = $.mobile.window,
				$el = this.element,
				scroll = $win.scrollTop(),
				elHeight = $el.height(),
				pHeight = $el.closest( ".ui-page" ).height(),
				viewportHeight = $.mobile.getScreenHeight(),
				tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer";

			return !notransition &&
				( this.options.transition && this.options.transition !== "none" &&
				(
					( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) ||
					( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight )
				) || this.options.fullscreen
				);
		},

		show: function( notransition ) {
			var hideClass = "ui-fixed-hidden",
				$el = this.element;

			if ( this._useTransition( notransition ) ) {
				$el
					.removeClass( "out " + hideClass )
					.addClass( "in" )
					.animationComplete(function () {
						$el.removeClass('in');
					});
			}
			else {
				$el.removeClass( hideClass );
			}
			this._visible = true;
		},

		hide: function( notransition ) {
			var hideClass = "ui-fixed-hidden",
				$el = this.element,
				// if it's a slide transition, our new transitions need the reverse class as well to slide outward
				outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" );

			if( this._useTransition( notransition ) ) {
				$el
					.addClass( outclass )
					.removeClass( "in" )
					.animationComplete(function() {
						$el.addClass( hideClass ).removeClass( outclass );
					});
			}
			else {
				$el.addClass( hideClass ).removeClass( outclass );
			}
			this._visible = false;
		},

		toggle: function() {
			this[ this._visible ? "hide" : "show" ]();
		},

		_bindToggleHandlers: function() {
			var self = this,
				o = self.options,
				$el = self.element,
				delayShow, delayHide,
				isVisible = true;

			// tap toggle
			$el.closest( ".ui-page" )
				.bind( "vclick", function( e ) {
					if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) {
						self.toggle();
					}
				})
				.bind( "focusin focusout", function( e ) {
					//this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which
					//positions fixed toolbars in the middle of the screen on pop if the input is near the top or
					//bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment
					//and issue #4113 Header and footer change their position after keyboard popup - iOS
					//and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment
					if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) {
						//Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system
						//controls causes fixed position, tap-toggle false Header to reveal itself
						// isVisible instead of self._visible because the focusin and focusout events fire twice at the same time
						// Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed
						// by a focusout when a native selects opens and the other way around when it closes.
						if ( e.type === "focusout" && !isVisible ) {
							isVisible = true;
							//wait for the stack to unwind and see if we have jumped to another input
							clearTimeout( delayHide );
							delayShow = setTimeout( function() {
								self.show();
							}, 0 );
						} else if ( e.type === "focusin" && !!isVisible ) {
							//if we have jumped to another input clear the time out to cancel the show.
							clearTimeout( delayShow );
							isVisible = false;
							delayHide = setTimeout( function() {
								self.hide();
							}, 0 );
						}
					}
				});
		},

		_destroy: function() {
			var $el = this.element,
				header = $el.hasClass( "ui-header" );

			$el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" );
			$el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" );
			$el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" );
		}

	});

	//auto self-init widgets
	$.mobile.document
		.bind( "pagecreate create", function( e ) {

			// DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element.
			// This line ensures it still works, but we recommend moving the attribute to the toolbars themselves.
			if ( $( e.target ).jqmData( "fullscreen" ) ) {
				$( $.mobile.fixedtoolbar.prototype.options.initSelector, e.target ).not( ":jqmData(fullscreen)" ).jqmData( "fullscreen", true );
			}

			$.mobile.fixedtoolbar.prototype.enhanceWithin( e.target );
		});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>


<commit_before>/**
 * jsmin - Refer to LICENSE in base directory
 * @param {String} input JavaScript to minifiy
 * @return {String} Minified JavaScript
 */
var jsminc = require('./jsmin.c');
function jsmin(input) {
  var EOF = -1,
      stdin = {
        'index': 0,
        'end': input.length,
        'read': function (len) {
          // For now only handle len = 1
          if (len !== 1) {
            throw new Error('You can only read one character from input at a time.');
          }

          // If we are at the end, return EOF (-1)
          var index = stdin.index;
          if (index === stdin.end) {
            return EOF;
          }

          // Read the input at our index
          var char = input[index];

          // Increment our index
          stdin.index = index + 1;

          // Return char
          return char;
        }
      },
      output = '',
      options = {
        'error': '',
        'stdout': function (str) {
          // Add the string to output
          output += str;
        },
        'stderr': function (err) {
          // Add the error to output
          options.error += err;
        },
        'exit': function (code) {
          // Throw the collective error
          throw new Error(options.error);
        }
      };

  // Run jsminc
  jsminc(stdin, options);

  // Return the output
  return output;
}

// Expose jsmin to the world
module.exports = jsmin;<commit_msg>Accidentally committed classic thought<commit_after><|endoftext|>


<commit_before>'use strict';
/*global document*/
 var React = require('react');
var keys = require('lodash/object/keys');
/**
 * Map containing all the mounted components.
 * @type {Object}
 */
var mountedComponents = require('./mounted-components');

var clearComponent = require('./clear');

/**
 *  Render a react component in a DOM selector.
 * @param {object} component - A react component.
 * @param {string} selector  - A selector on a DOM node.
 * @param {object} options   - Options for the component rendering.
 */
module.exports = function renderComponent(component, selector, options){
  options = options || {};
  // Clear a potential previously mounted component
  clearComponent(selector);
  let targetDOMContainer = document.querySelector(selector);
  if(!targetDOMContainer){throw new Error(`You are trying to render a component in a DOM element which is not existing, your selector is  ${selector}`); }
  // Render the component
  var mountedComponent = React.render(
    React.createElement(component, options.props, options.data),
    targetDOMContainer
  );
  //Save the fact that a component is mounted.
  mountedComponents[selector] = mountedComponent;
  console.info('Mounted components : ', keys(mountedComponents));
  return mountedComponent;
};
/*
  Exemple
  var render = Focus.application.render;
  var MyComponent = require('./my-component');
  render(MyComponent, 'div.component-container', {props: {id: '12'}});
 */
<commit_msg>[eslint] clean application/render<commit_after>/*global document*/
//dependencies
const React = require('react');
const keys = require('lodash/object/keys');
const mountedComponents = require('./mounted-components');
const clearComponent = require('./clear');

/**
*  Render a react component in a DOM selector.
* @param {object} component - A react component.
* @param {string} selector  - A selector on a DOM node.
* @param {object} options   - Options for the component rendering.
*/
module.exports = function renderComponent(component, selector, options){
    options = options || {};
    // Clear a potential previously mounted component
    clearComponent(selector);
    const targetDOMContainer = document.querySelector(selector);
    if(!targetDOMContainer){
        throw new Error(`You are trying to render a component in a DOM element which is not existing, your selector is  ${selector}`);
    }
    // Render the component
    const mountedComponent = React.render(
        React.createElement(component, options.props, options.data),
        targetDOMContainer
    );
    //Save the fact that a component is mounted.
    mountedComponents[selector] = mountedComponent;
    console.info('Mounted components : ', keys(mountedComponents));
    return mountedComponent;
};
/*
Exemple
var render = Focus.application.render;
var MyComponent = require('./my-component');
render(MyComponent, 'div.component-container', {props: {id: '12'}});
*/
<|endoftext|>


<commit_before>define(
  'ephox.darwin.navigation.CellFinder',

  [
    'ephox.perhaps.Option',
    'ephox.sugar.api.ElementFind',
    'ephox.sugar.api.SelectorFilter',
    'ephox.sugar.api.SelectorFind'
  ],

  function (Option, ElementFind, SelectorFilter, SelectorFind) {
    // IMPROVEMENT: Implement colspans and rowspans. Note, this will probably interact with snooker.

    var findInTable = function (cell) {
      return findColumn(cell).bind(function (cellInfo) {
        return findRow(cell).map(function (rowInfo) {
          return {
            rowIndex: rowInfo.index,
            colIndex: cellInfo.index,
          };
        });
      });
    };

    var findColumn = function (cell) {
      return ElementFind.inAncestorOfSelector(cell, 'tr', 'td,th');
    };

    var findRow = function (cell) {
      return SelectorFind.ancestor(cell, 'tr').bind(function (row) {
        return ElementFind.inAncestorOfSelector(row, 'table', 'tr');
      });
    };

    var gotoCell = function (table, rowIndex, colIndex) {
      var rows = SelectorFilter.descendants(table, 'tr');
      return Option.from(rows[rowIndex]).bind(function (row) {
        var cells = SelectorFilter.children(row, 'td,th');
        return Option.from(cells[colIndex]);
      });
    };

    return {
      findInTable: findInTable,
      gotoCell: gotoCell
    };
  }
);<commit_msg>TBIO-2621: Using ElementFind<commit_after>define(
  'ephox.darwin.navigation.CellFinder',

  [
    'ephox.perhaps.Option',
    'ephox.sugar.api.ElementFind',
    'ephox.sugar.api.SelectorFilter'
  ],

  function (Option, ElementFind, SelectorFilter) {
    // IMPROVEMENT: Implement colspans and rowspans. Note, this will probably interact with snooker.
    var findInTable = function (cell) {
      return ElementFind.inAncestorOfSelector(cell, 'tr', 'td,th').bind(function (cellInfo) {
        return ElementFind.inAncestorOfSelector(cellInfo.ancestor(), 'table', 'tr').map(function (rowInfo) {
          return {
            rowIndex: rowInfo.index,
            colIndex: cellInfo.index,
          };
        });
      });
    };

    var gotoCell = function (table, rowIndex, colIndex) {
      var rows = SelectorFilter.descendants(table, 'tr');
      return Option.from(rows[rowIndex]).bind(function (row) {
        var cells = SelectorFilter.children(row, 'td,th');
        return Option.from(cells[colIndex]);
      });
    };

    return {
      findInTable: findInTable,
      gotoCell: gotoCell
    };
  }
);<|endoftext|>


<commit_before>/*
 * ! ${copyright}
 */
/**
 * Constructor for a BaseAdapter
 *
 * @param {object} mMetadataContext a map containing meta data context
 * @param {sap.ui.model} mMetadataContext.model the current model
 * @param {string} mMetadataContext.path the absolute binding path without key information
 * @param {string} mMetadataContext.metaPath the path inside the meta model pointing to the binding
 * @param {string} mMetadataContext.modelName the name of the model
 * @param {string} mMetadataContext.contextName the name of the context
 * @param {object} mProperties the properties and redirection function
 * @returns {sap.ui.model.meta.BaseAdapter} an instance of a context specific adapter
 *
 * @experimental Since 1.58
 * @abstract
 */
sap.ui.define([
	"jquery.sap.global", "sap/ui/base/Object", "./AdapterConstants", "sap/ui/model/json/JSONModel", "sap/ui/base/SyncPromise"
], function(jQuery, BaseObject, AdapterConstants, JSONModel, SyncPromise) {
	"use strict";

	var BaseAdapter = BaseObject.extend("sap.ui.model.meta.BaseAdapter", {
		/**
		 * The reference to the current meta model.
		 *
		 * @protected
		 */
		oMetaModel: undefined,
		/**
		 * The models name
		 *
		 * @protected
		 */
		sModelName: undefined,
		constructor: function(mMetadataContext, mProperties) {
			this.constants = AdapterConstants;
			this.mMetadataContext = mMetadataContext;
			this.oModel = mMetadataContext.model;
			this.oMetaModel = this.oModel.getMetaModel();
			this.modelName = mMetadataContext.modelName;
			this.contextName = mMetadataContext.contextName;
			this.path = mMetadataContext.path;
			this.metaPath = mMetadataContext.metaPath;
			this._mProperties = {};
			this._mPropertyBag = {};
			this._mCustomPropertyBag = {};

			this.init();

			this.enhance(mProperties);
		},

		/**
		 * Enhance the adapter with certain properties
		 *
		 * @param {object} mProperties a may with "key" as property name, "fnValue" getter function
		 */
		enhance: function(mProperties) {
			if (mProperties) {
				for ( var sProperty in mProperties) {
					this.putProperty(sProperty, mProperties[sProperty]);
				}
			}
		},

		/**
		 * Individual init method for Adapters
		 *
		 * @protected
		 */
		init: function() {
			if (!this.metaPath) {
				this.oMetaContext = this.oMetaModel.getMetaContext(this.path);
				this.metaPath = this.oMetaContext.getPath();
			} else {
				this.oMetaContext = this.oMetaModel.createBindingContext(this.metaPath);
			}
		},
		/**
		 * The name of the model
		 *
		 * @return {string} the name of the model
		 */
		getModelName: function() {
			return this.modelName;
		},
		/**
		 * Puts a deferred property to the corresponding adapter
		 *
		 * @param {string} sProperty the name of an adapters property
		 * @param {object} vGetter a getter which can be either an object or a function
		 * @param {array} aArgs an optional array of arguments used if vGetter is a function
		 * @param {object} the caller that inhabits the vGetter function if not supplied the caller is the current closure
		 */
		putProperty: function(sProperty, vGetter, aArgs, caller) {
			if (!vGetter) {
				return;
			}

			if (!caller) {
				caller = this;
			}

			Object.defineProperty(this, sProperty, {
				configurable: true,
				get: function() {
					if (this._mCustomPropertyBag[sProperty]) {
						return this._mCustomPropertyBag[sProperty];
					}

					if (!this._mPropertyBag.hasOwnProperty(sProperty)) {
						this._mPropertyBag[sProperty] = new SyncPromise(function(resolve, reject) {
						if (typeof vGetter == 'function') {
								resolve(vGetter.apply(caller, aArgs));
						} else {
								resolve(vGetter);
						}
						});

					}

					return this._mPropertyBag[sProperty];
				},
				set: function(vValue) {
					this._mCustomPropertyBag[sProperty] = vValue;
				}
			});
		},
		/**
		 * The binding as a path within the model name
		 *
		 * @param {string} sValuePath the path to the property value, e.g 'Payed'
		 * @param {string} sType the optional name of the UI5 model type, e.g. 'sap.ui.model.type.string'
		 * @return {string} the representation of a simple binding syntax
		 */
		convertToSimpleBinding: function(sValuePath, sType) {
			var sPath = "{";

			if (this.modelName) {
				sPath = sPath + "model: '" + this.modelName + "',";
			}

			if (this.sContextPath && sValuePath.startsWith(this.sContextPath)) {
				sValuePath = sValuePath.replace(this.sContextPath,"");
			}

			sPath = sPath + "path: '" + sValuePath + "'";

			if (sType) {
				sPath = sPath + ", type: '" + sType + "'";
			}

			sPath = sPath + "}";

			return sPath;
		},
		/**
		 * Retrieves the context name
		 */
		getContext: function() {
			return this.contextName;
		},
		/**
		 *
		 */
		setValue: function(sProperty, vValue) {
			this.putProperty(sProperty, this._identity, [
				vValue
			], this);
		},
		_identity: function(vValue) {
			return vValue;
		},
		parentPromise: function(sParentModulePath, mMetadataContext) {
			return new Promise(function(resolve, reject) {
				sap.ui.require([
					sParentModulePath
				], function(ParentAdapter) {
					var oParent = new ParentAdapter(mMetadataContext);
					resolve(oParent);
				});
			});
		},
		getAdapterModel: function() {
			if (!this._oAdapterModel) {
				this._oAdapterModel = new JSONModel(this);
			}
			return this._oAdapterModel;
		},
		updateContextPath: function(oControl) {
			var oControlCtx = oControl.getBindingContext(this.model);
			var sContextPath = oControlCtx ? this.removeKeys(oControlCtx.getPath()) + "/" : null;
			if (sContextPath && sContextPath != this.sContextPath) {
				this.sContextPath = sContextPath;
				this._mPropertyBag = {};
			}
		},
		/**
		 *
		 * Removes the keys from the model/meta model path
		 *
		 * @param {string} sPath the path, e.g. /PurchaseOrders('300000020')
		 * @return {string} sKeyLess the key free path /PurchaseOrders
		 */
		removeKeys: function(sPath) {
			return sPath;
		}
	});

	return BaseAdapter;

});
<commit_msg>[INTERNAL] BaseAdapter: Fix escaping<commit_after>/*
 * ! ${copyright}
 */
/**
 * Constructor for a BaseAdapter
 *
 * @param {object} mMetadataContext a map containing meta data context
 * @param {sap.ui.model} mMetadataContext.model the current model
 * @param {string} mMetadataContext.path the absolute binding path without key information
 * @param {string} mMetadataContext.metaPath the path inside the meta model pointing to the binding
 * @param {string} mMetadataContext.modelName the name of the model
 * @param {string} mMetadataContext.contextName the name of the context
 * @param {object} mProperties the properties and redirection function
 * @returns {sap.ui.model.meta.BaseAdapter} an instance of a context specific adapter
 *
 * @experimental Since 1.58
 * @abstract
 */
sap.ui.define([
	"jquery.sap.global", "sap/ui/base/Object", "./AdapterConstants", "sap/ui/model/json/JSONModel", "sap/ui/base/SyncPromise"
], function(jQuery, BaseObject, AdapterConstants, JSONModel, SyncPromise) {
	"use strict";

	var BaseAdapter = BaseObject.extend("sap.ui.model.meta.BaseAdapter", {
		/**
		 * The reference to the current meta model.
		 *
		 * @protected
		 */
		oMetaModel: undefined,
		/**
		 * The models name
		 *
		 * @protected
		 */
		sModelName: undefined,
		constructor: function(mMetadataContext, mProperties) {
			this.constants = AdapterConstants;
			this.mMetadataContext = mMetadataContext;
			this.oModel = mMetadataContext.model;
			this.oMetaModel = this.oModel.getMetaModel();
			this.modelName = mMetadataContext.modelName;
			this.contextName = mMetadataContext.contextName;
			this.path = mMetadataContext.path;
			this.metaPath = mMetadataContext.metaPath;
			this._mProperties = {};
			this._mPropertyBag = {};
			this._mCustomPropertyBag = {};

			this.init();

			this.enhance(mProperties);
		},

		/**
		 * Enhance the adapter with certain properties
		 *
		 * @param {object} mProperties a may with "key" as property name, "fnValue" getter function
		 */
		enhance: function(mProperties) {
			if (mProperties) {
				for ( var sProperty in mProperties) {
					this.putProperty(sProperty, mProperties[sProperty]);
				}
			}
		},

		/**
		 * Individual init method for Adapters
		 *
		 * @protected
		 */
		init: function() {
			if (!this.metaPath) {
				this.oMetaContext = this.oMetaModel.getMetaContext(this.path);
				this.metaPath = this.oMetaContext.getPath();
			} else {
				this.oMetaContext = this.oMetaModel.createBindingContext(this.metaPath);
			}
		},
		/**
		 * The name of the model
		 *
		 * @return {string} the name of the model
		 */
		getModelName: function() {
			return this.modelName;
		},
		/**
		 * Puts a deferred property to the corresponding adapter
		 *
		 * @param {string} sProperty the name of an adapters property
		 * @param {object} vGetter a getter which can be either an object or a function
		 * @param {array} aArgs an optional array of arguments used if vGetter is a function
		 * @param {object} the caller that inhabits the vGetter function if not supplied the caller is the current closure
		 */
		putProperty: function(sProperty, vGetter, aArgs, caller) {
			if (!vGetter) {
				return;
			}

			if (!caller) {
				caller = this;
			}

			Object.defineProperty(this, sProperty, {
				configurable: true,
				get: function() {
					if (this._mCustomPropertyBag[sProperty]) {
						return this._mCustomPropertyBag[sProperty];
					}

					if (!this._mPropertyBag.hasOwnProperty(sProperty)) {
						this._mPropertyBag[sProperty] = new SyncPromise(function(resolve, reject) {
						if (typeof vGetter == 'function') {
								resolve(vGetter.apply(caller, aArgs));
						} else {
								resolve(vGetter);
						}
						});

					}

					return this._mPropertyBag[sProperty];
				},
				set: function(vValue) {
					this._mCustomPropertyBag[sProperty] = vValue;
				}
			});
		},
		/**
		 * The binding as a path within the model name
		 *
		 * @param {string} sValuePath the path to the property value, e.g 'Payed'
		 * @param {string} sType the optional name of the UI5 model type, e.g. 'sap.ui.model.type.string'
		 * @return {string} the representation of a simple binding syntax
		 */
		convertToSimpleBinding: function(sValuePath, sType) {
			var sPath = "{";

			if (this.modelName) {
				sPath = sPath + "model: '" + this.modelName + "',";
			}

			if (this.sContextPath && sValuePath.startsWith(this.sContextPath)) {
				sValuePath = sValuePath.replace(this.sContextPath,"");
			}

			sPath = sPath + "path: '" + escape(sValuePath) + "'";

			if (sType) {
				sPath = sPath + ", type: '" + sType + "'";
			}

			sPath = sPath + "}";

			return sPath;
		},
		/**
		 * Retrieves the context name
		 */
		getContext: function() {
			return this.contextName;
		},
		/**
		 *
		 */
		setValue: function(sProperty, vValue) {
			this.putProperty(sProperty, this._identity, [
				vValue
			], this);
		},
		_identity: function(vValue) {
			return vValue;
		},
		parentPromise: function(sParentModulePath, mMetadataContext) {
			return new Promise(function(resolve, reject) {
				sap.ui.require([
					sParentModulePath
				], function(ParentAdapter) {
					var oParent = new ParentAdapter(mMetadataContext);
					resolve(oParent);
				});
			});
		},
		getAdapterModel: function() {
			if (!this._oAdapterModel) {
				this._oAdapterModel = new JSONModel(this);
			}
			return this._oAdapterModel;
		},
		updateContextPath: function(oControl) {
			var oControlCtx = oControl.getBindingContext(this.model);
			var sContextPath = oControlCtx ? this.removeKeys(oControlCtx.getPath()) + "/" : null;
			if (sContextPath && sContextPath != this.sContextPath) {
				this.sContextPath = sContextPath;
				this._mPropertyBag = {};
			}
		},
		/**
		 *
		 * Removes the keys from the model/meta model path
		 *
		 * @param {string} sPath the path, e.g. /PurchaseOrders('300000020')
		 * @return {string} sKeyLess the key free path /PurchaseOrders
		 */
		removeKeys: function(sPath) {
			return sPath;
		}
	});

	return BaseAdapter;

});
<|endoftext|>


<commit_before>/*jshint esversion: 6 */
/* globals process */
const nThen = require("nthen");
const getFolderSize = require("get-folder-size");
const Util = require("../common-util");
const Ulimit = require("ulimit");
const Decrees = require("../decrees");

var Fs = require("fs");

var Admin = module.exports;

var getFileDescriptorCount = function (Env, server, cb) {
    Fs.readdir('/proc/self/fd', function(err, list) {
        if (err) { return void cb(err); }
        cb(void 0, list.length);
    });
};

var getFileDescriptorLimit = function (env, server, cb) {
    Ulimit(cb);
};

var getCacheStats = function (env, server, cb) {
    var metaSize = 0;
    var channelSize = 0;
    var metaCount = 0;
    var channelCount = 0;

    try {
        var meta = env.metadata_cache;
        for (var x in meta) {
            if (meta.hasOwnProperty(x)) {
                metaCount++;
                metaSize += JSON.stringify(meta[x]).length;
            }
        }

        var channels = env.channel_cache;
        for (var y in channels) {
            if (channels.hasOwnProperty(y)) {
                channelCount++;
                channelSize += JSON.stringify(channels[y]).length;
            }
        }
    } catch (err) {
        return void cb(err && err.message);
    }

    cb(void 0, {
        metadata: metaCount,
        metaSize: metaSize,
        channel: channelCount,
        channelSize: channelSize,
        memoryUsage: process.memoryUsage(),
    });
};

var getActiveSessions = function (Env, Server, cb) {
    var stats = Server.getSessionStats();
    cb(void 0, [
        stats.total,
        stats.unique
    ]);
};

var shutdown = function (Env, Server, cb) {
    if (true) {
        return void cb('E_NOT_IMPLEMENTED');
    }

    // disconnect all users and reject new connections
    Server.shutdown();

    // stop all intervals that may be running
    Object.keys(Env.intervals).forEach(function (name) {
        clearInterval(Env.intervals[name]);
    });

    // set a flag to prevent incoming database writes
    // wait until all pending writes are complete
    // then process.exit(0);
    // and allow system functionality to restart the server
};

var getRegisteredUsers = function (Env, Server, cb) {
    Env.batchRegisteredUsers('', cb, function (done) {
        var dir = Env.paths.pin;
        var folders;
        var users = 0;
        nThen(function (waitFor) {
            Fs.readdir(dir, waitFor(function (err, list) {
                if (err) {
                    waitFor.abort();
                    return void done(err);
                }
                folders = list;
            }));
        }).nThen(function (waitFor) {
            folders.forEach(function (f) {
                var dir = Env.paths.pin + '/' + f;
                Fs.readdir(dir, waitFor(function (err, list) {
                    if (err) { return; }
                    users += list.length;
                }));
            });
        }).nThen(function () {
            done(void 0, users);
        });
    });
};

var getDiskUsage = function (Env, Server, cb) {
    Env.batchDiskUsage('', cb, function (done) {
        var data = {};
        nThen(function (waitFor) {
            getFolderSize('./', waitFor(function(err, info) {
                data.total = info;
            }));
            getFolderSize(Env.paths.pin, waitFor(function(err, info) {
                data.pin = info;
            }));
            getFolderSize(Env.paths.blob, waitFor(function(err, info) {
                data.blob = info;
            }));
            getFolderSize(Env.paths.staging, waitFor(function(err, info) {
                data.blobstage = info;
            }));
            getFolderSize(Env.paths.block, waitFor(function(err, info) {
                data.block = info;
            }));
            getFolderSize(Env.paths.data, waitFor(function(err, info) {
                data.datastore = info;
            }));
        }).nThen(function () {
            done(void 0, data);
        });
    });
};

var getActiveChannelCount = function (Env, Server, cb) {
    cb(void 0, Server.getActiveChannelCount());
};

var flushCache = function (Env, Server,  cb) {
    Env.flushCache();
    cb(void 0, true);
};

// CryptPad_AsyncStore.rpc.send('ADMIN', ['ARCHIVE_DOCUMENT', documentID], console.log)
var archiveDocument = function (Env, Server, cb, data) {
    var id = Array.isArray(data) && data[1];
    if (typeof(id) !== 'string' || id.length < 32) { return void cb("EINVAL"); }

    switch (id.length) {
        case 32:
        // TODO disconnect users from active sessions
            return void Env.msgStore.archiveChannel(id, cb);
        case 48:
            return void Env.blobStore.archive.blob(id, cb);
        default:
            return void cb("INVALID_ID_LENGTH");
    }

    // archival for blob proofs isn't automated, but evict-inactive.js will
    // clean up orpaned blob proofs
    // Env.blobStore.archive.proof(userSafeKey, blobId, cb)
};

var restoreArchivedDocument = function (Env, Server, cb) {
    // Env.msgStore.restoreArchivedChannel(channelName, cb)
    // Env.blobStore.restore.blob(blobId, cb)
    // Env.blobStore.restore.proof(userSafekey, blobId, cb)

    cb("NOT_IMPLEMENTED");
};

// CryptPad_AsyncStore.rpc.send('ADMIN', [ 'ADMIN_DECREE', ['RESTRICT_REGISTRATION', [true]]], console.log)
var adminDecree = function (Env, Server, cb, data, unsafeKey) {
    var value = data[1];
    if (!Array.isArray(value)) { return void cb('INVALID_DECREE'); }

    var command = value[0];
    var args = value[1];

/*

The admin should have sent a command to be run:

the server adds two pieces of information to the supplied decree:

* the unsafeKey of the admin who uploaded it
* the current time

1. test the command to see if it's valid and will result in a change
2. if so, apply it and write it to the log for persistence
3. respond to the admin with an error or nothing

*/

    var decree = [command, args, unsafeKey, +new Date()];
    var changed;
    try {
        changed = Decrees.handleCommand(Env, decree) || false;
    } catch (err) {
        return void cb(err);
    }

    if (!changed) { return void cb(); }
    Decrees.write(Env, decree, cb);
};

// CryptPad_AsyncStore.rpc.send('ADMIN', ['INSTANCE_STATUS], console.log)
var instanceStatus = function (Env, Server, cb) {
    cb(void 0, {
        restrictRegistration: Boolean(Env.restrictRegistration),
        launchTime: Env.launchTime,
        currentTime: +new Date(),

        accountRetentionTime: Env.accountRetentionTime,
        archiveRetentionTime: Env.archiveRetentionTime,

        defaultStorageLimit: Env.defaultStorageLimit,
    });
};

// CryptPad_AsyncStore.rpc.send('ADMIN', ['GET_LIMITS'], console.log)
var getLimits = function (Env, Server, cb) {
    cb(void 0, Env.limits);
};

var commands = {
    ACTIVE_SESSIONS: getActiveSessions,
    ACTIVE_PADS: getActiveChannelCount,
    REGISTERED_USERS: getRegisteredUsers,
    DISK_USAGE: getDiskUsage,
    FLUSH_CACHE: flushCache,
    SHUTDOWN: shutdown,
    GET_FILE_DESCRIPTOR_COUNT: getFileDescriptorCount,
    GET_FILE_DESCRIPTOR_LIMIT: getFileDescriptorLimit,
    GET_CACHE_STATS: getCacheStats,

    ARCHIVE_DOCUMENT: archiveDocument,
    RESTORE_ARCHIVED_DOCUMENT: restoreArchivedDocument,

    ADMIN_DECREE: adminDecree,
    INSTANCE_STATUS: instanceStatus,
    GET_LIMITS: getLimits,
};

Admin.command = function (Env, safeKey, data, _cb, Server) {
    var cb = Util.once(Util.mkAsync(_cb));

    var admins = Env.admins;

    var unsafeKey = Util.unescapeKeyCharacters(safeKey);
    if (admins.indexOf(unsafeKey) === -1) {
        return void cb("FORBIDDEN");
    }

    var command = commands[data[0]];

    if (typeof(command) === 'function') {
        return void command(Env, Server, cb, data, unsafeKey);
    }

    return void cb('UNHANDLED_ADMIN_COMMAND');
};

<commit_msg>report lastEviction in an admin INSTANCE_STATUS<commit_after>/*jshint esversion: 6 */
/* globals process */
const nThen = require("nthen");
const getFolderSize = require("get-folder-size");
const Util = require("../common-util");
const Ulimit = require("ulimit");
const Decrees = require("../decrees");

var Fs = require("fs");

var Admin = module.exports;

var getFileDescriptorCount = function (Env, server, cb) {
    Fs.readdir('/proc/self/fd', function(err, list) {
        if (err) { return void cb(err); }
        cb(void 0, list.length);
    });
};

var getFileDescriptorLimit = function (env, server, cb) {
    Ulimit(cb);
};

var getCacheStats = function (env, server, cb) {
    var metaSize = 0;
    var channelSize = 0;
    var metaCount = 0;
    var channelCount = 0;

    try {
        var meta = env.metadata_cache;
        for (var x in meta) {
            if (meta.hasOwnProperty(x)) {
                metaCount++;
                metaSize += JSON.stringify(meta[x]).length;
            }
        }

        var channels = env.channel_cache;
        for (var y in channels) {
            if (channels.hasOwnProperty(y)) {
                channelCount++;
                channelSize += JSON.stringify(channels[y]).length;
            }
        }
    } catch (err) {
        return void cb(err && err.message);
    }

    cb(void 0, {
        metadata: metaCount,
        metaSize: metaSize,
        channel: channelCount,
        channelSize: channelSize,
        memoryUsage: process.memoryUsage(),
    });
};

var getActiveSessions = function (Env, Server, cb) {
    var stats = Server.getSessionStats();
    cb(void 0, [
        stats.total,
        stats.unique
    ]);
};

var shutdown = function (Env, Server, cb) {
    if (true) {
        return void cb('E_NOT_IMPLEMENTED');
    }

    // disconnect all users and reject new connections
    Server.shutdown();

    // stop all intervals that may be running
    Object.keys(Env.intervals).forEach(function (name) {
        clearInterval(Env.intervals[name]);
    });

    // set a flag to prevent incoming database writes
    // wait until all pending writes are complete
    // then process.exit(0);
    // and allow system functionality to restart the server
};

var getRegisteredUsers = function (Env, Server, cb) {
    Env.batchRegisteredUsers('', cb, function (done) {
        var dir = Env.paths.pin;
        var folders;
        var users = 0;
        nThen(function (waitFor) {
            Fs.readdir(dir, waitFor(function (err, list) {
                if (err) {
                    waitFor.abort();
                    return void done(err);
                }
                folders = list;
            }));
        }).nThen(function (waitFor) {
            folders.forEach(function (f) {
                var dir = Env.paths.pin + '/' + f;
                Fs.readdir(dir, waitFor(function (err, list) {
                    if (err) { return; }
                    users += list.length;
                }));
            });
        }).nThen(function () {
            done(void 0, users);
        });
    });
};

var getDiskUsage = function (Env, Server, cb) {
    Env.batchDiskUsage('', cb, function (done) {
        var data = {};
        nThen(function (waitFor) {
            getFolderSize('./', waitFor(function(err, info) {
                data.total = info;
            }));
            getFolderSize(Env.paths.pin, waitFor(function(err, info) {
                data.pin = info;
            }));
            getFolderSize(Env.paths.blob, waitFor(function(err, info) {
                data.blob = info;
            }));
            getFolderSize(Env.paths.staging, waitFor(function(err, info) {
                data.blobstage = info;
            }));
            getFolderSize(Env.paths.block, waitFor(function(err, info) {
                data.block = info;
            }));
            getFolderSize(Env.paths.data, waitFor(function(err, info) {
                data.datastore = info;
            }));
        }).nThen(function () {
            done(void 0, data);
        });
    });
};

var getActiveChannelCount = function (Env, Server, cb) {
    cb(void 0, Server.getActiveChannelCount());
};

var flushCache = function (Env, Server,  cb) {
    Env.flushCache();
    cb(void 0, true);
};

// CryptPad_AsyncStore.rpc.send('ADMIN', ['ARCHIVE_DOCUMENT', documentID], console.log)
var archiveDocument = function (Env, Server, cb, data) {
    var id = Array.isArray(data) && data[1];
    if (typeof(id) !== 'string' || id.length < 32) { return void cb("EINVAL"); }

    switch (id.length) {
        case 32:
        // TODO disconnect users from active sessions
            return void Env.msgStore.archiveChannel(id, cb);
        case 48:
            return void Env.blobStore.archive.blob(id, cb);
        default:
            return void cb("INVALID_ID_LENGTH");
    }

    // archival for blob proofs isn't automated, but evict-inactive.js will
    // clean up orpaned blob proofs
    // Env.blobStore.archive.proof(userSafeKey, blobId, cb)
};

var restoreArchivedDocument = function (Env, Server, cb) {
    // Env.msgStore.restoreArchivedChannel(channelName, cb)
    // Env.blobStore.restore.blob(blobId, cb)
    // Env.blobStore.restore.proof(userSafekey, blobId, cb)

    cb("NOT_IMPLEMENTED");
};

// CryptPad_AsyncStore.rpc.send('ADMIN', [ 'ADMIN_DECREE', ['RESTRICT_REGISTRATION', [true]]], console.log)
var adminDecree = function (Env, Server, cb, data, unsafeKey) {
    var value = data[1];
    if (!Array.isArray(value)) { return void cb('INVALID_DECREE'); }

    var command = value[0];
    var args = value[1];

/*

The admin should have sent a command to be run:

the server adds two pieces of information to the supplied decree:

* the unsafeKey of the admin who uploaded it
* the current time

1. test the command to see if it's valid and will result in a change
2. if so, apply it and write it to the log for persistence
3. respond to the admin with an error or nothing

*/

    var decree = [command, args, unsafeKey, +new Date()];
    var changed;
    try {
        changed = Decrees.handleCommand(Env, decree) || false;
    } catch (err) {
        return void cb(err);
    }

    if (!changed) { return void cb(); }
    Decrees.write(Env, decree, cb);
};

// CryptPad_AsyncStore.rpc.send('ADMIN', ['INSTANCE_STATUS], console.log)
var instanceStatus = function (Env, Server, cb) {
    cb(void 0, {
        restrictRegistration: Boolean(Env.restrictRegistration),
        launchTime: Env.launchTime,
        currentTime: +new Date(),

        accountRetentionTime: Env.accountRetentionTime,
        archiveRetentionTime: Env.archiveRetentionTime,

        defaultStorageLimit: Env.defaultStorageLimit,

        lastEviction: Env.lastEviction,
    });
};

// CryptPad_AsyncStore.rpc.send('ADMIN', ['GET_LIMITS'], console.log)
var getLimits = function (Env, Server, cb) {
    cb(void 0, Env.limits);
};

var commands = {
    ACTIVE_SESSIONS: getActiveSessions,
    ACTIVE_PADS: getActiveChannelCount,
    REGISTERED_USERS: getRegisteredUsers,
    DISK_USAGE: getDiskUsage,
    FLUSH_CACHE: flushCache,
    SHUTDOWN: shutdown,
    GET_FILE_DESCRIPTOR_COUNT: getFileDescriptorCount,
    GET_FILE_DESCRIPTOR_LIMIT: getFileDescriptorLimit,
    GET_CACHE_STATS: getCacheStats,

    ARCHIVE_DOCUMENT: archiveDocument,
    RESTORE_ARCHIVED_DOCUMENT: restoreArchivedDocument,

    ADMIN_DECREE: adminDecree,
    INSTANCE_STATUS: instanceStatus,
    GET_LIMITS: getLimits,
};

Admin.command = function (Env, safeKey, data, _cb, Server) {
    var cb = Util.once(Util.mkAsync(_cb));

    var admins = Env.admins;

    var unsafeKey = Util.unescapeKeyCharacters(safeKey);
    if (admins.indexOf(unsafeKey) === -1) {
        return void cb("FORBIDDEN");
    }

    var command = commands[data[0]];

    if (typeof(command) === 'function') {
        return void command(Env, Server, cb, data, unsafeKey);
    }

    return void cb('UNHANDLED_ADMIN_COMMAND');
};

<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Custom-styled native input/buttons
//>>label: Buttons: Input or button-based
//>>group: Forms
//>>css.structure: ../css/structure/jquery.mobile.button.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../../jquery.mobile.widget", "../../jquery.mobile.buttonMarkup"  ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.widget( "mobile.button", $.mobile.widget, {
	options: {
		theme: null,
		icon: null,
		iconpos: null,
		corners: true,
		shadow: true,
		iconshadow: true,
		inline: null,
		mini: null,
		initSelector: "button, [type='button'], [type='submit'], [type='reset']"
	},
	_create: function() {
		var $el = this.element,
			$button,
			// create a copy of this.options we can pass to buttonMarkup
			o = ( function( tdo ) {
				var key, ret = {};

				for ( key in tdo ) {
					if ( tdo[ key ] !== null && key !== "initSelector" ) {
						ret[ key ] = tdo[ key ];
					}
				}

				return ret;
			} )( this.options ),
			classes = "",
			$buttonPlaceholder;

		// if this is a link, check if it's been enhanced and, if not, use the right function
		if ( $el[ 0 ].tagName === "A" ) {
			if ( !$el.hasClass( "ui-btn" ) ) {
				$el.buttonMarkup();
			}
			return;
		}

		// get the inherited theme
		// TODO centralize for all widgets
		if ( !this.options.theme ) {
			this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
		}

		// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
		/* if ( $el[0].className.length ) {
			classes = $el[0].className;
		} */
		if ( !!~$el[0].className.indexOf( "ui-btn-left" ) ) {
			classes = "ui-btn-left";
		}

		if (  !!~$el[0].className.indexOf( "ui-btn-right" ) ) {
			classes = "ui-btn-right";
		}

		if (  $el.attr( "type" ) === "submit" || $el.attr( "type" ) === "reset" ) {
			classes ? classes += " ui-submit" :  classes = "ui-submit";
		}
		$( "label[for='" + $el.attr( "id" ) + "']" ).addClass( "ui-submit" );

		// Add ARIA role
		this.button = $( "

" )
			[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() )
			.insertBefore( $el )
			.buttonMarkup( o )
			.addClass( classes )
			.append( $el.addClass( "ui-btn-hidden" ) );

        $button = this.button;

		$el.bind({
			focus: function() {
				$button.addClass( $.mobile.focusClass );
			},

			blur: function() {
				$button.removeClass( $.mobile.focusClass );
			}
		});

		this.refresh();
	},

	_setOption: function( key, value ) {
		var op = {};

		op[ key ] = value;
		if ( key !== "initSelector" ) {
			this.button.buttonMarkup( op );
			// Record the option change in the options and in the DOM data-* attributes
			this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
		}
		this._super( "_setOption", key, value );
	},

	enable: function() {
		this.element.attr( "disabled", false );
		this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
		return this._setOption( "disabled", false );
	},

	disable: function() {
		this.element.attr( "disabled", true );
		this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true );
		return this._setOption( "disabled", true );
	},

	refresh: function() {
		var $el = this.element;

		if ( $el.prop("disabled") ) {
			this.disable();
		} else {
			this.enable();
		}

		// Grab the button's text element from its implementation-independent data item
		$( this.button.data( 'buttonElements' ).text )[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() );
	}
});

//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
	$.mobile.button.prototype.enhanceWithin( e.target, true );
});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>Button: remove duplicated call to buttonMarkup<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Custom-styled native input/buttons
//>>label: Buttons: Input or button-based
//>>group: Forms
//>>css.structure: ../css/structure/jquery.mobile.button.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../../jquery.mobile.widget", "../../jquery.mobile.buttonMarkup"  ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.widget( "mobile.button", $.mobile.widget, {
	options: {
		theme: null,
		icon: null,
		iconpos: null,
		corners: true,
		shadow: true,
		iconshadow: true,
		inline: null,
		mini: null,
		initSelector: "button, [type='button'], [type='submit'], [type='reset']"
	},
	_create: function() {
		var $el = this.element,
			$button,
			o,
			classes = "";

		// if this is a link, check if it's been enhanced and, if not, use the right function
		if ( $el[ 0 ].tagName === "A" ) {
			if ( !$el.hasClass( "ui-btn" ) ) {
				$el.buttonMarkup();
			}
			return;
		}
		// create a copy of this.options we can pass to buttonMarkup
		o = ( function( tdo ) {
			var key, ret = {};

			for ( key in tdo ) {
				if ( tdo[ key ] !== null && key !== "initSelector" ) {
					ret[ key ] = tdo[ key ];
				}
			}

			return ret;
		} )( this.options );

		// get the inherited theme
		// TODO centralize for all widgets
		if ( !this.options.theme ) {
			this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
		}

		// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
		/* if ( $el[0].className.length ) {
			classes = $el[0].className;
		} */
		if ( !!~$el[0].className.indexOf( "ui-btn-left" ) ) {
			classes = "ui-btn-left";
		}

		if (  !!~$el[0].className.indexOf( "ui-btn-right" ) ) {
			classes = "ui-btn-right";
		}

		if (  $el.attr( "type" ) === "submit" || $el.attr( "type" ) === "reset" ) {
			classes ? classes += " ui-submit" :  classes = "ui-submit";
		}
		$( "label[for='" + $el.attr( "id" ) + "']" ).addClass( "ui-submit" );

		o.disabled = $el.prop("disabled");
		// Add ARIA role
		this.button = $( "

" )
			[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() )
			.insertBefore( $el )
			.buttonMarkup( o )
			.addClass( classes )
			.append( $el.addClass( "ui-btn-hidden" ) );

        $button = this.button;

		$el.bind({
			focus: function() {
				$button.addClass( $.mobile.focusClass );
			},

			blur: function() {
				$button.removeClass( $.mobile.focusClass );
			}
		});

		this._initialRefresh = true;
		this.refresh();
		this._initialRefresh = false;
	},

	_setOption: function( key, value ) {
		var op = {};

		op[ key ] = value;
		if ( key !== "initSelector" ) {
			if (!this._initialRefresh) {
				//make sure buttonMarkup is called only once on create
				this.button.buttonMarkup( op );
			}
			// Record the option change in the options and in the DOM data-* attributes
			this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
		}
		this._super( "_setOption", key, value );
	},

	enable: function() {
		this.element.attr( "disabled", false );
		this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
		return this._setOption( "disabled", false );
	},

	disable: function() {
		this.element.attr( "disabled", true );
		this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true );
		return this._setOption( "disabled", true );
	},

	refresh: function() {
		var $el = this.element;

		if ( $el.prop("disabled") ) {
			this.disable();
		} else {
			this.enable();
		}

		// Grab the button's text element from its implementation-independent data item
		$( this.button.data( 'buttonElements' ).text )[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() );
	}
});

//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
	$.mobile.button.prototype.enhanceWithin( e.target, true );
});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>


<commit_before>import React from 'react';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import {Table, Column, Cell} from 'fixed-data-table';
import TextCell from './TextCell';
import NumbericColorCell from './NumbericColorCell.js';
import '../node_modules/fixed-data-table/dist/fixed-data-table.min.css';

const Stocks = ({ data: { loading, stocks } }) => {
  if (loading) {
    return
Loading...
;
  } else {
    const headerHeight = 50;
    const rowHeight = 50;
    const height = stocks.length * rowHeight + headerHeight;
    return (

{'Stock Ticker'}

          <Column
            header={<Cell>Symbol</Cell>}
            cell={<TextCell data={stocks} field="symbol" />
            }
            width={200}
          />

          <Column
            header={<Cell>{'Company Name'}</Cell>}
            cell={<TextCell data={stocks} field="companyName" />
            }
            width={200}
          />

          <Column
            header={<Cell>Price</Cell>}
            cell={<TextCell data={stocks} field="price" />
            }
            width={200}
          />

          <Column
            header={<Cell>Change</Cell>}
            cell={<TextCell data={stocks} field="symbol" />
            }
            width={200}
          />

          <Column
            header={<Cell>{'% Change'}</Cell>}
            cell={<TextCell data={stocks} field="changePct" />
            }
            width={200}
          />

    );
  }
};

export default graphql(gql`
  query StocksQuery {
    stocks {
      companyName,
      symbol,
      price,
      change,
      changePct,
      openPrice,
      marketCap,
      exchange,
    }
  }
`
)(Stocks);
<commit_msg>repush<commit_after>import React from 'react';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import {Table, Column, Cell} from 'fixed-data-table';
import TextCell from './TextCell';
import NumbericColorCell from './NumbericColorCell.js';
import '../node_modules/fixed-data-table/dist/fixed-data-table.min.css';

const Stocks = ({ data: { loading, stocks } }) => {
  if (loading) {
    return
Loading...
;
  } else {
    const headerHeight = 50;
    const rowHeight = 50;
    const height = stocks.length * rowHeight + headerHeight;
    return (

{'Stock Ticker'}

          <Column
            header={<Cell>Symbol</Cell>}
            cell={<TextCell data={stocks} field="symbol" />
            }
            width={200}
          />

          <Column
            header={<Cell>{'Company Name'}</Cell>}
            cell={<TextCell data={stocks} field="companyName" />
            }
            width={200}
          />

          <Column
            header={<Cell>Price</Cell>}
            cell={<TextCell data={stocks} field="price" />
            }
            width={200}
          />

          <Column
            header={<Cell>Change</Cell>}
            cell={<TextCell data={stocks} field="symbol" />
            }
            width={200}
          />

          <Column
            header={<Cell>{'% Change'}</Cell>}
            cell={<TextCell data={stocks} field="changePct" />
            }
            width={200}
          />

    );
  }
};

export default graphql(gql`
  query StocksQuery {
    stocks {
      companyName,
      symbol,
      price,
      change,
      changePct,
      openPrice,
      marketCap,
      exchange,
    }
  }
`
)(Stocks);
<|endoftext|>


<commit_before>'use strict';

var
  jsonld = require('jsonld'),
  RDFa = require('jsonld/js/rdfa');

var JsonLdParser = function (rdf, options) {
  options = options || {};

  if (!('importPrefixMap' in options)) {
    options.importPrefixMap = true;
  }

  var jsonldExpandFlat = function (data, base, callback) {
    jsonld.expand(data, {'base': base}, function (error, expanded) {
      if (error) {
        return callback(null, error.message);
      }

      jsonld.flatten(expanded, {}, function (error, flattened) {
        if (error) {
          return callback(null, error.message);
        }

        if (!('@graph' in flattened)) {
          return callback(null);
        }

        callback(flattened['@graph']);
      });
    });
  };

  var toArray = function (object) {
    object = object || [];

    if (Array.isArray(object)) {
      return object;
    }

    return [object];
  };

  this.process = function (data, callback, base, filter, done) {
    if (typeof data === 'string') {
      data = JSON.parse(data);
    }

    base = base || '';
    filter = filter || function () { return true; };
    done = done || function () {};

    var getLiteral = function (jNode) {
      var
        type = null,
        lang = null;

      if ('@type' in jNode) {
        type = getNode(jNode['@type']);
      }

      if ('@language' in jNode) {
        lang = jNode['@language'];
      }

      return rdf.createLiteral(jNode['@value'], lang, type);
    };

    var nodeCache = {};

    var getNode = function (jNode) {
      // is there already a node?
      if (jNode in nodeCache) {
        return nodeCache[jNode];
      }

      // is it a blank node?
      if (!jNode) {
        return rdf.createBlankNode();
      }

      if (jNode.indexOf('_:') === 0) {
        return (nodeCache[jNode] = rdf.createBlankNode());
      }

      // if not it's a named node
      return (nodeCache[jNode] = rdf.createNamedNode(jNode));
    };

    var pushTriple = function (subject, predicate, object) {
      var triple = rdf.createTriple(subject, predicate, object);

      if (filter(triple)) {
        callback(triple);
      }
    };

    var processSubject = function (jSubject) {
      var
        subject = jSubject['@id'],
        types = toArray(jSubject['@type']);

      // add type triples
      types.forEach(function (type) {
        pushTriple(
          getNode(subject),
          getNode(rdf.ns.type),
          getNode(type));
      });

      // other triples
      for (var predicate in jSubject) {
        // ignore JSON-LD properties
        if (predicate.indexOf('@') === 0) {
          continue;
        }

        processPredicate(subject, predicate, toArray(jSubject[predicate]));
      }
    };

    var processPredicate = function (subject, predicate, jObjects) {
      jObjects.forEach(function (jObject) {
        pushTriple(
          getNode(subject),
          getNode(predicate),
          processObject(jObject));
      });
    };

    var processObject = function (jObject) {
      // is it a simple literal?
      if (typeof jObject === 'string') {
        return rdf.createLiteral(jObject);
      }

      // or blank node / named node
      if ('@id' in jObject) {
        return getNode(jObject['@id']);
      }

      if ('@list' in jObject) {
        return processList(jObject['@list']);
      }

      // or complex literal
      return getLiteral(jObject);
    };

    var processList = function (jList) {
      var
        entry = getNode(),
        subject = entry,
        rest;

      jList.forEach(function (jItem, index) {
        if (index !== jList.length-1) {
          rest = getNode();
        } else {
          rest = getNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#nil');
        }

        pushTriple(
          subject,
          getNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#first'),
          getNode(jItem['@id']));

        pushTriple(
          subject,
          getNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#rest'),
          rest);

        subject = rest;
      });

      return entry;
    };

    if (options.importPrefixMap && '@context' in data && typeof data['@context'] === 'object') {
      var context = data['@context'];

      Object.keys(context).forEach(function (key) {
        if (key.slice(1) !== '@' && typeof context[key] === 'string') {
          rdf.prefixes[key] = context[key];
        }
      });
    }

    jsonldExpandFlat(data, base, function (jGraph, error) {
      if (error) {
        return done(false, error);
      }

      if (!jGraph) {
        return done(true);
      }

      jGraph.forEach(function (jSubject) {
        processSubject(jSubject);
      });

      done(true);
    });

    return true;
  };

  this.parse = function (data, callback, base, filter, graph) {
    graph = graph || rdf.createGraph();

    return this.process(
      data,
      function (triple) { graph.add(triple); },
      base,
      filter,
      function (success, error) { callback(success ? graph : null, error); });
  };
};

var RdfaParser = function (rdf) {
  var jsonLdParser = new JsonLdParser(rdf);

  this.parse = function (rdfaData, callback, base, filter, graph) {
    if (typeof rdfaData === 'string') {
      try {
        rdfaData = rdf.parseHtml(rdfaData);
      } catch (error) {
        callback(null, error);

        return false;
      }
    }

    graph = graph || rdf.createGraph();

    rdfaData.location = { href: base };
    RDFa.attach(rdfaData);

    jsonld.fromRDF(rdfaData.data, {format: 'rdfa-api'}, function (error, jsonLdData) {
      if (error) {
        callback(null, error);
      } else {
        jsonLdParser.process(
          jsonLdData,
          function (triple) {
            graph.add(triple);
          },
          base,
          filter,
          function (success, error) {
            callback(success ? graph : null, error);
          });
      }
    });

    return true;
  };
};

module.exports = function (rdf) {
  rdf.JsonLdParser = JsonLdParser.bind(null, rdf);

  var jsonLdParser = new JsonLdParser(rdf);
  rdf.parseJsonLd = jsonLdParser.parse.bind(jsonLdParser);

  rdf.utils.mimeTypeParserMap['application/ld+json'] = rdf.parseJsonLd;

  rdf.RdfaParser = RdfaParser.bind(null, rdf);

  var rdfaParser = new RdfaParser(rdf);
  rdf.parseRdfa = rdfaParser.parse.bind(rdfaParser);
};
<commit_msg>fixed error which cause import of JSON-LD context properties with leading @ into prefix map<commit_after>'use strict';

var
  jsonld = require('jsonld'),
  RDFa = require('jsonld/js/rdfa');

var JsonLdParser = function (rdf, options) {
  options = options || {};

  if (!('importPrefixMap' in options)) {
    options.importPrefixMap = true;
  }

  var jsonldExpandFlat = function (data, base, callback) {
    jsonld.expand(data, {'base': base}, function (error, expanded) {
      if (error) {
        return callback(null, error.message);
      }

      jsonld.flatten(expanded, {}, function (error, flattened) {
        if (error) {
          return callback(null, error.message);
        }

        if (!('@graph' in flattened)) {
          return callback(null);
        }

        callback(flattened['@graph']);
      });
    });
  };

  var toArray = function (object) {
    object = object || [];

    if (Array.isArray(object)) {
      return object;
    }

    return [object];
  };

  this.process = function (data, callback, base, filter, done) {
    if (typeof data === 'string') {
      data = JSON.parse(data);
    }

    base = base || '';
    filter = filter || function () { return true; };
    done = done || function () {};

    var getLiteral = function (jNode) {
      var
        type = null,
        lang = null;

      if ('@type' in jNode) {
        type = getNode(jNode['@type']);
      }

      if ('@language' in jNode) {
        lang = jNode['@language'];
      }

      return rdf.createLiteral(jNode['@value'], lang, type);
    };

    var nodeCache = {};

    var getNode = function (jNode) {
      // is there already a node?
      if (jNode in nodeCache) {
        return nodeCache[jNode];
      }

      // is it a blank node?
      if (!jNode) {
        return rdf.createBlankNode();
      }

      if (jNode.indexOf('_:') === 0) {
        return (nodeCache[jNode] = rdf.createBlankNode());
      }

      // if not it's a named node
      return (nodeCache[jNode] = rdf.createNamedNode(jNode));
    };

    var pushTriple = function (subject, predicate, object) {
      var triple = rdf.createTriple(subject, predicate, object);

      if (filter(triple)) {
        callback(triple);
      }
    };

    var processSubject = function (jSubject) {
      var
        subject = jSubject['@id'],
        types = toArray(jSubject['@type']);

      // add type triples
      types.forEach(function (type) {
        pushTriple(
          getNode(subject),
          getNode(rdf.ns.type),
          getNode(type));
      });

      // other triples
      for (var predicate in jSubject) {
        // ignore JSON-LD properties
        if (predicate.indexOf('@') === 0) {
          continue;
        }

        processPredicate(subject, predicate, toArray(jSubject[predicate]));
      }
    };

    var processPredicate = function (subject, predicate, jObjects) {
      jObjects.forEach(function (jObject) {
        pushTriple(
          getNode(subject),
          getNode(predicate),
          processObject(jObject));
      });
    };

    var processObject = function (jObject) {
      // is it a simple literal?
      if (typeof jObject === 'string') {
        return rdf.createLiteral(jObject);
      }

      // or blank node / named node
      if ('@id' in jObject) {
        return getNode(jObject['@id']);
      }

      if ('@list' in jObject) {
        return processList(jObject['@list']);
      }

      // or complex literal
      return getLiteral(jObject);
    };

    var processList = function (jList) {
      var
        entry = getNode(),
        subject = entry,
        rest;

      jList.forEach(function (jItem, index) {
        if (index !== jList.length-1) {
          rest = getNode();
        } else {
          rest = getNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#nil');
        }

        pushTriple(
          subject,
          getNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#first'),
          getNode(jItem['@id']));

        pushTriple(
          subject,
          getNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#rest'),
          rest);

        subject = rest;
      });

      return entry;
    };

    if (options.importPrefixMap && '@context' in data && typeof data['@context'] === 'object') {
      var context = data['@context'];

      Object.keys(context).forEach(function (key) {
        if (key.slice(0, 1) !== '@' && typeof context[key] === 'string') {
          rdf.prefixes[key] = context[key];
        }
      });
    }

    jsonldExpandFlat(data, base, function (jGraph, error) {
      if (error) {
        return done(false, error);
      }

      if (!jGraph) {
        return done(true);
      }

      jGraph.forEach(function (jSubject) {
        processSubject(jSubject);
      });

      done(true);
    });

    return true;
  };

  this.parse = function (data, callback, base, filter, graph) {
    graph = graph || rdf.createGraph();

    return this.process(
      data,
      function (triple) { graph.add(triple); },
      base,
      filter,
      function (success, error) { callback(success ? graph : null, error); });
  };
};

var RdfaParser = function (rdf) {
  var jsonLdParser = new JsonLdParser(rdf);

  this.parse = function (rdfaData, callback, base, filter, graph) {
    if (typeof rdfaData === 'string') {
      try {
        rdfaData = rdf.parseHtml(rdfaData);
      } catch (error) {
        callback(null, error);

        return false;
      }
    }

    graph = graph || rdf.createGraph();

    rdfaData.location = { href: base };
    RDFa.attach(rdfaData);

    jsonld.fromRDF(rdfaData.data, {format: 'rdfa-api'}, function (error, jsonLdData) {
      if (error) {
        callback(null, error);
      } else {
        jsonLdParser.process(
          jsonLdData,
          function (triple) {
            graph.add(triple);
          },
          base,
          filter,
          function (success, error) {
            callback(success ? graph : null, error);
          });
      }
    });

    return true;
  };
};

module.exports = function (rdf) {
  rdf.JsonLdParser = JsonLdParser.bind(null, rdf);

  var jsonLdParser = new JsonLdParser(rdf);
  rdf.parseJsonLd = jsonLdParser.parse.bind(jsonLdParser);

  rdf.utils.mimeTypeParserMap['application/ld+json'] = rdf.parseJsonLd;

  rdf.RdfaParser = RdfaParser.bind(null, rdf);

  var rdfaParser = new RdfaParser(rdf);
  rdf.parseRdfa = rdfaParser.parse.bind(rdfaParser);
};
<|endoftext|>


<commit_before>var filter = "All";
var tasks = [];

$(document).ready(function(){
  $("#parallax").parallax()
  var fire = new Firebase('https://ucdd2bookuno.firebaseio.com')
  fire.child('todos/').on('value', function(snapshot){
    tasks = snapshot.val();
    loadData(tasks,filter);
  })
});

function updateFilter(filternew){
  filter = filternew;
  loadData(tasks, filter);
}

function loadData(tasks,filter)
  {
    var header = $('#header');
    if( filter == 'Low'){
      header.text('Low Priority Tasks')
    }
    else if(filter == 'Medium'){
      header.text('Medium Priority Tasks')
    }
    else if( filter == 'High'){
      header.text('High Priority Tasks')
    }
    else if( filter == 'Complete'){
      header.text('Completed Tasks')
    }
    else{
      header.text('Tasks')
    }
    $('#tasks').empty();
    tasks.forEach(function(task){
              console.log(task.completed = false)
              if ((task.priority == filter || filter == "All") || (filter == "Complete" && task.complete == true))
              {

                    if (task.completed == false)
                    {
                          $('#tasks').append(
                              '
'+
                              '
'
                              +'
'+
                              ''+
                              ''+ task.title + ''+'
Deadline: '+task.deadline+'        Priority: '+ task.priority +'  Type: '+ task.type +'
' + '
'
                              +'
'+'Complete\'
'+

                              '
'+
                              '
')

                    }

                    if (task.complete == true)
                    {
                          $('#tasks').append(
                              '
'+
                              '
'
                              +'
'+
                              ''+ task.title + ''+'
Complete: ' + task.completed + '+
Deadline: '+task.deadline+'        Priority: '+ task.priority +'  Type: '+ task.type +'
' + '
'
                              +'
'+'Complete\'
'+

                              '
'+
                              '
')
                    }

                    }

                  })
  }<commit_msg>large icon<commit_after>var filter = "All";
var tasks = [];

$(document).ready(function(){
  $("#parallax").parallax()
  var fire = new Firebase('https://ucdd2bookuno.firebaseio.com')
  fire.child('todos/').on('value', function(snapshot){
    tasks = snapshot.val();
    loadData(tasks,filter);
  })
});

function updateFilter(filternew){
  filter = filternew;
  loadData(tasks, filter);
}

function loadData(tasks,filter)
  {
    var header = $('#header');
    if( filter == 'Low'){
      header.text('Low Priority Tasks')
    }
    else if(filter == 'Medium'){
      header.text('Medium Priority Tasks')
    }
    else if( filter == 'High'){
      header.text('High Priority Tasks')
    }
    else if( filter == 'Complete'){
      header.text('Completed Tasks')
    }
    else{
      header.text('Tasks')
    }
    $('#tasks').empty();
    tasks.forEach(function(task){
              console.log(task.completed = false)
              if ((task.priority == filter || filter == "All") || (filter == "Complete" && task.complete == true))
              {

                    if (task.completed == false)
                    {
                          $('#tasks').append(
                              '
'+
                              '
'
                              +'
'+
                              ''+
                              ''+ task.title + ''+'
Deadline: '+task.deadline+'        Priority: '+ task.priority +'  Type: '+ task.type +'
' + '
'
                              +'
'+'Complete\'
'+

                              '
'+
                              '
')

                    }

                    if (task.complete == true)
                    {
                          $('#tasks').append(
                              '
'+
                              '
'
                              +'
'+
                              ''+ task.title + ''+'
Complete: ' + task.completed + '+
Deadline: '+task.deadline+'        Priority: '+ task.priority +'  Type: '+ task.type +'
' + '
'
                              +'
'+'Complete\'
'+

                              '
'+
                              '
')
                    }

                    }

                  })
  }<|endoftext|>


<commit_before><commit_msg>Signed-off-by: JJ Taylor <j.taylor@moesol.com><commit_after><|endoftext|>