<commit_before>;(function( factory ){
	// CommonJS
	if ( typeof module !== "undefined" && module && module.exports ) {
		module.exports = factory();

	// RequireJS
	} else if ( typeof define === "function" && define.amd ) {
		define( factory );

	// global
	} else {
		P = factory();
	}
})(function() {
	"use strict";

	var
		// linked list with head node - used as a queue of tasks
		// f: task, w: needed a tick, n: next node
		head = { f: null, w: false, n: null }, tail = head,

		// vars for tick re-usage
		nextNeedsTick = true, pendingTicks = 0, neededTicks = 0,

		channel, // MessageChannel
		requestTick, // requestTick( onTick, 0 ) is the only valid usage!

		// window or worker
		wow = ot(typeof window) && window || ot(typeof worker) && worker,

		toStr = head.toString,
		isArray,

		ALT = {};

	function onTick() {
		--pendingTicks;
		if ( head.n ) {
			if ( !pendingTicks && head.n.n ) {
				// In case of multiple tasks, ensure at least one successive tick
				// to handle remaining task in case one throws, even if specified it will not.
				++pendingTicks;
				requestTick( onTick, 0 );
			}
			do {
				head = head.n;
				if ( head.w ) {
					--neededTicks;
				}
				var f = head.f;
				head.f = null;
				f();
			} while ( head.n )
		}
		nextNeedsTick = true;
	}

	function runLater( f, couldThrow ) {
		if ( nextNeedsTick && ++neededTicks > pendingTicks ) {
			++pendingTicks;
			requestTick( onTick, 0 );
		};
		tail = tail.n = { f: f, w: nextNeedsTick, n: null };
		nextNeedsTick = couldThrow === true;
	}

	function ot( type ) {
		return type === "object" || type === "function";
	}

	function ft( type ) {
		return type === "function";
	}

	if ( ot(typeof process) && process && ft(typeof process.nextTick) ) {
		requestTick = process.nextTick;

	} else if ( wow && ft(typeof wow.setImmediate) ) {
		requestTick = function( cb ) {
			wow.setImmediate( cb );
		};

	} else if ( ft(typeof MessageChannel) ) {
		channel = new MessageChannel();
		channel.port1.onmessage = onTick;
		requestTick = function() {
			channel.port2.postMessage(0);
		};

	} else {
		requestTick = setTimeout;

		if ( wow && ot(typeof Image) && Image ) {
			(function(){
				var c = 0;

				var requestTickViaImage = function( cb ) {
					var img = new Image();
					img.onerror = cb;
					img.src = 'data:image/png,';
				};

				// Before using it, test if it works properly, with async dispatching.
				try {
					requestTickViaImage(function() {
						if ( --c === 0 ) {
							requestTick = requestTickViaImage;
						}
					});
					++c;
				} catch (e) {}

				// Also use it only if faster then setTimeout.
				c && setTimeout(function() {
					c = 0;
				}, 0);
			})();
		}
	}

	//__________________________________________________________________________

	isArray = Array.isArray || function( val ) {
		return !!val && toStr.call( val ) === "[object Array]";
	};

	function forEach( arr, cb ) {
		for ( var i = 0, l = arr.length; i < l; ++i ) {
			if ( i in arr ) {
				cb( arr[i], i );
			}
		}
	}

	function each( obj, cb ) {
		if ( isArray(obj) ) {
			forEach( obj, cb );
			return;
		}

		for ( var prop in obj ) {
			cb( obj[prop], prop );
		}
	}

	function P( val ) {
		if ( val instanceof Promise ) {
			return val;
		}

		var def = defer();
		def.resolve( val );
		return def.promise;
	}

	P.defer = defer;
	function defer() {
		var pending = [],
			rejected = false,
			promise = new Promise( then ),
			value;

		function then( onFulfilled, onRejected, alt, altDef ) {
			var def = alt === ALT ? altDef : defer();

			function onReslved() {
				var func = rejected ? onRejected : onFulfilled;

				if ( !def ) {
					func && func( value );
					return;
				}

				if ( typeof func === "function" ) {
					try {
						var res = func( value );
					} catch ( ex ) {
						def.reject( ex );
					}

					def.resolve( res );

				} else if ( rejected ) {
					def.reject( value );

				} else {
					def.fulfill( value );
				}
			}

			if ( pending ) {
				pending.push( onReslved );

			} else {
				runLater( onReslved );
			}

			return def && def.promise;
		}

		function resolve( val ) {
			if ( pending ) {
				if ( val instanceof Promise ) {
					val.then( fulfill, reject, ALT );

				} else if ( val && typeof val.then === "function" ) {
					runLater(function() {
						try {
							val.then( fulfill, reject );
						} catch ( ex ) {
							reject( ex );
						}
					});

				} else {
					fulfill( val );
				}
			}
		}

		function fulfill( val ) {
			if ( pending ) {
				promise.state = rejected ? "rejected" : "fulfilled";
				promise.value = value = val;
				forEach( pending, runLater );
				pending = null;
			}
		}

		function reject( error ) {
			if ( pending ) {
				rejected = true;
				fulfill( error );
			}
		}

		return {
			promise: promise,
			resolve: resolve,
			fulfill: fulfill,
			reject: reject
		};
	}

	function Promise( then ) {
		this.then = then;
		this.state = "pending";
		this.value = void 0;
	}

	Promise.prototype.done = function( cb, eb ) {
		var p = this;
		if ( cb || eb ) {
			p = p.then( cb, eb );
		}
		p.then(null, function( error ) {
			runLater(function() {
				if ( P.onerror ) {
					P.onerror( error );
				} else {
					throw error;
				}
			}, true);
		}, ALT);
	};

	Promise.prototype.spread = function( cb, eb ) {
		return this.then(cb && function( values ) {
			return cb.apply( void 0, values );
		}, eb);
	};

	Promise.prototype.timeout = function( ms ) {
		var def = defer();
		var timeoutId = setTimeout(function() {
			def.reject( new Error("Timed out after " + ms + " ms") );
		}, ms);

		this.when(function( value ) {
			clearTimeout( timeoutId );
			def.fulfill( value );
		}, function( error ) {
			clearTimeout( timeoutId );
			def.reject( error );
		}, ALT);

		return def.promise;
	};

	Promise.prototype.delay = function( ms ) {
		var self = this;
		var def = defer();
		setTimeout(function() {
			def.resolve( self );
		}, ms);
		return def.promise;
	};

	P.all = all;
	function all( promises ) {
		var waiting = 0;
		var def = defer();
		each( promises, function( promise, index ) {
			++waiting;
			P( promise ).then(function( value ) {
				promises[ index ] = value;
				if ( --waiting === 0 ) {
					def.fulfill( promises );
				}
			}, def.reject, ALT );
		});
		if ( waiting === 0 ) {
			def.fulfill( promises );
		}
		return def.promise;
	}

	P.allResolved = allResolved;
	function allResolved( promises ) {
		var waiting = 1;
		var def = defer();
		function callback() {
			if ( --waiting === 0 ) {
				def.fulfill( promises );
			}
		}
		each( promises, function( promise, index ) {
			++waiting;
			promises[ index ] = promise = P( promise );
			promise.then( callback, callback, ALT );
		});
		callback();
		return def.promise;
	}

	P.onerror = null;

	P.prototype = Promise.prototype;

	P.nextTick = function( f ) {
		runLater( f, true );
	};

	P.ALT = ALT;

	//P.runLater = runLater;

	return P;
});
<commit_msg>Rename onResolved to onSettled.<commit_after>;(function( factory ){
	// CommonJS
	if ( typeof module !== "undefined" && module && module.exports ) {
		module.exports = factory();

	// RequireJS
	} else if ( typeof define === "function" && define.amd ) {
		define( factory );

	// global
	} else {
		P = factory();
	}
})(function() {
	"use strict";

	var
		// linked list with head node - used as a queue of tasks
		// f: task, w: needed a tick, n: next node
		head = { f: null, w: false, n: null }, tail = head,

		// vars for tick re-usage
		nextNeedsTick = true, pendingTicks = 0, neededTicks = 0,

		channel, // MessageChannel
		requestTick, // requestTick( onTick, 0 ) is the only valid usage!

		// window or worker
		wow = ot(typeof window) && window || ot(typeof worker) && worker,

		toStr = head.toString,
		isArray,

		ALT = {};

	function onTick() {
		--pendingTicks;
		if ( head.n ) {
			if ( !pendingTicks && head.n.n ) {
				// In case of multiple tasks, ensure at least one successive tick
				// to handle remaining task in case one throws, even if specified it will not.
				++pendingTicks;
				requestTick( onTick, 0 );
			}
			do {
				head = head.n;
				if ( head.w ) {
					--neededTicks;
				}
				var f = head.f;
				head.f = null;
				f();
			} while ( head.n )
		}
		nextNeedsTick = true;
	}

	function runLater( f, couldThrow ) {
		if ( nextNeedsTick && ++neededTicks > pendingTicks ) {
			++pendingTicks;
			requestTick( onTick, 0 );
		};
		tail = tail.n = { f: f, w: nextNeedsTick, n: null };
		nextNeedsTick = couldThrow === true;
	}

	function ot( type ) {
		return type === "object" || type === "function";
	}

	function ft( type ) {
		return type === "function";
	}

	if ( ot(typeof process) && process && ft(typeof process.nextTick) ) {
		requestTick = process.nextTick;

	} else if ( wow && ft(typeof wow.setImmediate) ) {
		requestTick = function( cb ) {
			wow.setImmediate( cb );
		};

	} else if ( ft(typeof MessageChannel) ) {
		channel = new MessageChannel();
		channel.port1.onmessage = onTick;
		requestTick = function() {
			channel.port2.postMessage(0);
		};

	} else {
		requestTick = setTimeout;

		if ( wow && ot(typeof Image) && Image ) {
			(function(){
				var c = 0;

				var requestTickViaImage = function( cb ) {
					var img = new Image();
					img.onerror = cb;
					img.src = 'data:image/png,';
				};

				// Before using it, test if it works properly, with async dispatching.
				try {
					requestTickViaImage(function() {
						if ( --c === 0 ) {
							requestTick = requestTickViaImage;
						}
					});
					++c;
				} catch (e) {}

				// Also use it only if faster then setTimeout.
				c && setTimeout(function() {
					c = 0;
				}, 0);
			})();
		}
	}

	//__________________________________________________________________________

	isArray = Array.isArray || function( val ) {
		return !!val && toStr.call( val ) === "[object Array]";
	};

	function forEach( arr, cb ) {
		for ( var i = 0, l = arr.length; i < l; ++i ) {
			if ( i in arr ) {
				cb( arr[i], i );
			}
		}
	}

	function each( obj, cb ) {
		if ( isArray(obj) ) {
			forEach( obj, cb );
			return;
		}

		for ( var prop in obj ) {
			cb( obj[prop], prop );
		}
	}

	function P( val ) {
		if ( val instanceof Promise ) {
			return val;
		}

		var def = defer();
		def.resolve( val );
		return def.promise;
	}

	P.defer = defer;
	function defer() {
		var pending = [],
			rejected = false,
			promise = new Promise( then ),
			value;

		function then( onFulfilled, onRejected, alt, altDef ) {
			var def = alt === ALT ? altDef : defer();

			function onSettled() {
				var func = rejected ? onRejected : onFulfilled;

				if ( !def ) {
					func && func( value );
					return;
				}

				if ( typeof func === "function" ) {
					try {
						var res = func( value );
					} catch ( ex ) {
						def.reject( ex );
					}

					def.resolve( res );

				} else if ( rejected ) {
					def.reject( value );

				} else {
					def.fulfill( value );
				}
			}

			if ( pending ) {
				pending.push( onSettled );

			} else {
				runLater( onSettled );
			}

			return def && def.promise;
		}

		function resolve( val ) {
			if ( pending ) {
				if ( val instanceof Promise ) {
					val.then( fulfill, reject, ALT );

				} else if ( val && typeof val.then === "function" ) {
					runLater(function() {
						try {
							val.then( fulfill, reject );
						} catch ( ex ) {
							reject( ex );
						}
					});

				} else {
					fulfill( val );
				}
			}
		}

		function fulfill( val ) {
			if ( pending ) {
				promise.state = rejected ? "rejected" : "fulfilled";
				promise.value = value = val;
				forEach( pending, runLater );
				pending = null;
			}
		}

		function reject( error ) {
			if ( pending ) {
				rejected = true;
				fulfill( error );
			}
		}

		return {
			promise: promise,
			resolve: resolve,
			fulfill: fulfill,
			reject: reject
		};
	}

	function Promise( then ) {
		this.then = then;
		this.state = "pending";
		this.value = void 0;
	}

	Promise.prototype.done = function( cb, eb ) {
		var p = this;
		if ( cb || eb ) {
			p = p.then( cb, eb );
		}
		p.then(null, function( error ) {
			runLater(function() {
				if ( P.onerror ) {
					P.onerror( error );
				} else {
					throw error;
				}
			}, true);
		}, ALT);
	};

	Promise.prototype.spread = function( cb, eb ) {
		return this.then(cb && function( values ) {
			return cb.apply( void 0, values );
		}, eb);
	};

	Promise.prototype.timeout = function( ms ) {
		var def = defer();
		var timeoutId = setTimeout(function() {
			def.reject( new Error("Timed out after " + ms + " ms") );
		}, ms);

		this.when(function( value ) {
			clearTimeout( timeoutId );
			def.fulfill( value );
		}, function( error ) {
			clearTimeout( timeoutId );
			def.reject( error );
		}, ALT);

		return def.promise;
	};

	Promise.prototype.delay = function( ms ) {
		var self = this;
		var def = defer();
		setTimeout(function() {
			def.resolve( self );
		}, ms);
		return def.promise;
	};

	P.all = all;
	function all( promises ) {
		var waiting = 0;
		var def = defer();
		each( promises, function( promise, index ) {
			++waiting;
			P( promise ).then(function( value ) {
				promises[ index ] = value;
				if ( --waiting === 0 ) {
					def.fulfill( promises );
				}
			}, def.reject, ALT );
		});
		if ( waiting === 0 ) {
			def.fulfill( promises );
		}
		return def.promise;
	}

	P.allResolved = allResolved;
	function allResolved( promises ) {
		var waiting = 1;
		var def = defer();
		function callback() {
			if ( --waiting === 0 ) {
				def.fulfill( promises );
			}
		}
		each( promises, function( promise, index ) {
			++waiting;
			promises[ index ] = promise = P( promise );
			promise.then( callback, callback, ALT );
		});
		callback();
		return def.promise;
	}

	P.onerror = null;

	P.prototype = Promise.prototype;

	P.nextTick = function( f ) {
		runLater( f, true );
	};

	P.ALT = ALT;

	//P.runLater = runLater;

	return P;
});
<|endoftext|>


<commit_before>const checkForDuplicateIssue = require('./utils/check-for-duplicate-issue')
const handlerSetup = require('./utils/handler-setup')
const { assignFlow, endDiff } = require('./utils/helpers')
const parseDiff = require('./utils/parse-diff')
const reopenClosed = require('./utils/reopen-closed')
const { issue } = require('./templates')

module.exports = async context => {
  // Only trigger push handler on pushes to master
  if (context.payload.ref !== `refs/heads/${context.payload.repository.master_branch}`) {
    return
  }

  // Do not trigger on merge commits
  const commit = await context.github.gitdata.getCommit(context.repo({sha: context.payload.head_commit.id}))
  if (commit.data.parents.length > 1) return

  const [
    { regex, config, labels },
    { data: diff }
  ] = await Promise.all([
    handlerSetup(context),
    context.github.repos.getCommit(context.repo({
      sha: context.payload.head_commit.id,
      headers: { Accept: 'application/vnd.github.diff' }
    }))
  ])

  let match
  while ((match = regex.exec(endDiff(diff))) !== null) {
    const parsed = parseDiff({ match, context, config })

    if (parsed.filename === '.github/config.yml') continue

    // Prevent duplicates
    const existingIssue = await checkForDuplicateIssue(context, parsed.title)
    if (existingIssue) {
      context.log(`Duplicate issue found with title [${parsed.title}]`)
      await reopenClosed({ context, config, issue: existingIssue }, parsed)
      continue
    }

    let body = issue(context.repo({
      sha: parsed.sha,
      assignedToString: parsed.assignedToString,
      range: parsed.range,
      filename: parsed.filename,
      keyword: parsed.keyword,
      body: parsed.body
    }))

    const replace_br_regEx = /\/?<br(?:\s\/)?>/g
    body = body.replace(replace_br_regEx,'
')
    context.log(`Creating issue [${parsed.title}] in [${context.repo().owner}/${context.repo().repo}`)
    await context.github.issues.create(context.repo({ title: parsed.title, body, labels, ...assignFlow(config, parsed.username) }))
  }
}
<commit_msg>Fix typo<commit_after>const checkForDuplicateIssue = require('./utils/check-for-duplicate-issue')
const handlerSetup = require('./utils/handler-setup')
const { assignFlow, endDiff } = require('./utils/helpers')
const parseDiff = require('./utils/parse-diff')
const reopenClosed = require('./utils/reopen-closed')
const { issue } = require('./templates')

module.exports = async context => {
  // Only trigger push handler on pushes to master
  if (context.payload.ref !== `refs/heads/${context.payload.repository.master_branch}`) {
    return
  }

  // Do not trigger on merge commits
  const commit = await context.github.gitdata.getCommit(context.repo({sha: context.payload.head_commit.id}))
  if (commit.data.parents.length > 1) return

  const [
    { regex, config, labels },
    { data: diff }
  ] = await Promise.all([
    handlerSetup(context),
    context.github.repos.getCommit(context.repo({
      sha: context.payload.head_commit.id,
      headers: { Accept: 'application/vnd.github.diff' }
    }))
  ])

  let match
  while ((match = regex.exec(endDiff(diff))) !== null) {
    const parsed = parseDiff({ match, context, config })

    if (parsed.filename === '.github/config.yml') continue

    // Prevent duplicates
    const existingIssue = await checkForDuplicateIssue(context, parsed.title)
    if (existingIssue) {
      context.log(`Duplicate issue found with title [${parsed.title}]`)
      await reopenClosed({ context, config, issue: existingIssue }, parsed)
      continue
    }

    let body = issue(context.repo({
      sha: parsed.sha,
      assignedToString: parsed.assignedToString,
      range: parsed.range,
      filename: parsed.filename,
      keyword: parsed.keyword,
      body: parsed.body
    }))

    const replace_br_regEx = /\/?<br(?:\s\/)?>/g
    body = body.replace(replace_br_regEx,'
')
    context.log(`Creating issue [${parsed.title}] in [${context.repo().owner}/${context.repo().repo}]`)
    await context.github.issues.create(context.repo({ title: parsed.title, body, labels, ...assignFlow(config, parsed.username) }))
  }
}
<|endoftext|>


<commit_before>/**
 * https://github.com/facebook/react-native/blob/master/Libraries/react-native/react-native.js
 */
import React from 'react';

import createMockComponent from './components/createMockComponent';

// Export React, plus some native additions.
const ReactNative = {
  // Components
  ActivityIndicatorIOS: createMockComponent('ActivityIndicatorIOS'),
  ART: require('./components/ART'),
  DatePickerIOS: createMockComponent('DatePickerIOS'),
  DrawerLayoutAndroid: createMockComponent('DrawerLayoutAndroid'),
  Image: require('./components/Image'),
  ImageEditor: createMockComponent('ImageEditor'),
  ImageStore: createMockComponent('ImageStore'),
  ListView: createMockComponent('ListView'),
  MapView: createMockComponent('MapView'),
  Modal: createMockComponent('Modal'),
  Navigator: createMockComponent('Navigator'),
  NavigatorIOS: createMockComponent('NavigatorIOS'),
  Picker: createMockComponent('Picker'),
  PickerIOS: createMockComponent('PickerIOS'),
  ProgressBarAndroid: createMockComponent('ProgressBarAndroid'),
  ProgressViewIOS: createMockComponent('ProgressViewIOS'),
  ScrollView: require('./components/ScrollView'),
  SegmentedControlIOS: createMockComponent('SegmentedControlIOS'),
  SliderIOS: createMockComponent('SliderIOS'),
  SnapshotViewIOS: createMockComponent('SnapshotViewIOS'),
  Switch: createMockComponent('Switch'),
  PullToRefreshViewAndroid: createMockComponent('PullToRefreshViewAndroid'),
  RecyclerViewBackedScrollView: createMockComponent('RecyclerViewBackedScrollView'),
  RefreshControl: createMockComponent('RefreshControl'),
  SwitchAndroid: createMockComponent('SwitchAndroid'),
  SwitchIOS: createMockComponent('SwitchIOS'),
  TabBarIOS: createMockComponent('TabBarIOS'),
  Text: require('./components/Text'),
  TextInput: require('./components/TextInput'),
  ToastAndroid: createMockComponent('ToastAndroid'),
  ToolbarAndroid: createMockComponent('ToolbarAndroid'),
  Touchable: createMockComponent('Touchable'),
  TouchableHighlight: createMockComponent('TouchableHighlight'),
  TouchableNativeFeedback: createMockComponent('TouchableNativeFeedback'),
  TouchableOpacity: createMockComponent('TouchableOpacity'),
  TouchableWithoutFeedback: createMockComponent('TouchableWithoutFeedback'),
  View: require('./components/View'),
  ViewPagerAndroid: createMockComponent('ViewPagerAndroid'),
  WebView: require('./components/WebView'),

  // APIs
  ActionSheetIOS: require('./api/ActionSheetIOS'),
  Alert: require('./api/Alert'),
  AlertIOS: require('./api/AlertIOS'),
  Animated: require('./api/Animated'),
  AppRegistry: require('./api/AppRegistry'),
  AppState: require('./api/AppState'),
  AppStateIOS: require('./api/AppStateIOS'),
  AsyncStorage: require('./api/AsyncStorage'),
  BackAndroid: require('./api/BackAndroid'),
  CameraRoll: require('./api/CameraRoll'),
  Clipboard: require('./NativeModules/Clipboard'),
  DatePickerAndroid: require('./api/DatePickerAndroid'),
  Dimensions: require('./api/Dimensions'),
  Easing: require('./api/Animated/Easing'),
  ImagePickerIOS: require('./api/ImagePickerIOS'),
  IntentAndroid: require('./api/IntentAndroid'),
  InteractionManager: require('./api/InteractionManager'),
  LayoutAnimation: require('./api/LayoutAnimation'),
  Linking: require('./api/Linking'),
  LinkingIOS: require('./api/LinkingIOS'),
  NetInfo: require('./api/NetInfo'),
  PanResponder: require('./api/PanResponder'),
  PixelRatio: require('./api/PixelRatio'),
  PushNotificationIOS: require('./api/PushNotificationIOS'),
  Settings: require('./api/Settings'),
  StatusBarIOS: require('./api/StatusBarIOS'),
  StyleSheet: require('./api/StyleSheet'),
  TimePickerAndroid: require('./api/TimePickerAndroid'),
  UIManager: require('./NativeModules/UIManager'),
  VibrationIOS: require('./api/VibrationIOS'),

  // Plugins
  DeviceEventEmitter: require('./plugins/DeviceEventEmitter'),
  NativeAppEventEmitter: require('./plugins/NativeAppEventEmitter'),
  NativeModules: require('./NativeModules'),
  Platform: require('./plugins/Platform'),
  processColor: require('./plugins/processColor'),
  requireNativeComponent: require('./plugins/requireNativeComponent'),

  // Prop Types
  ColorPropType: require('./propTypes/ColorPropType'),
  EdgeInsetsPropType: require('./propTypes/EdgeInsetsPropType'),
  PointPropType: require('./propTypes/PointPropType'),
};

// See http://facebook.github.io/react/docs/addons.html
const ReactNativeAddons = {
  LinkedStateMixin: require('react-addons-linked-state-mixin'),
  Perf: require('react-addons-perf'),
  PureRenderMixin: require('react-addons-pure-render-mixin'),
  TestModule: require('./NativeModules/TestModule'),
  TestUtils: require('react-addons-test-utils'),
  // TODO(lmr): not sure where to find this
  // batchedUpdates: require('ReactUpdates').batchedUpdates,
  cloneWithProps: require('react-addons-clone-with-props'),
  createFragment: require('react-addons-create-fragment'),
  update: require('react-addons-update'),
};

Object.assign(ReactNative, React, { addons: ReactNativeAddons });

module.exports = ReactNative;
<commit_msg>Actually use listview mock component<commit_after>/**
 * https://github.com/facebook/react-native/blob/master/Libraries/react-native/react-native.js
 */
import React from 'react';

import createMockComponent from './components/createMockComponent';

// Export React, plus some native additions.
const ReactNative = {
  // Components
  ActivityIndicatorIOS: createMockComponent('ActivityIndicatorIOS'),
  ART: require('./components/ART'),
  DatePickerIOS: createMockComponent('DatePickerIOS'),
  DrawerLayoutAndroid: createMockComponent('DrawerLayoutAndroid'),
  Image: require('./components/Image'),
  ImageEditor: createMockComponent('ImageEditor'),
  ImageStore: createMockComponent('ImageStore'),
  ListView: require('./components/ListView'),
  MapView: createMockComponent('MapView'),
  Modal: createMockComponent('Modal'),
  Navigator: createMockComponent('Navigator'),
  NavigatorIOS: createMockComponent('NavigatorIOS'),
  Picker: createMockComponent('Picker'),
  PickerIOS: createMockComponent('PickerIOS'),
  ProgressBarAndroid: createMockComponent('ProgressBarAndroid'),
  ProgressViewIOS: createMockComponent('ProgressViewIOS'),
  ScrollView: require('./components/ScrollView'),
  SegmentedControlIOS: createMockComponent('SegmentedControlIOS'),
  SliderIOS: createMockComponent('SliderIOS'),
  SnapshotViewIOS: createMockComponent('SnapshotViewIOS'),
  Switch: createMockComponent('Switch'),
  PullToRefreshViewAndroid: createMockComponent('PullToRefreshViewAndroid'),
  RecyclerViewBackedScrollView: createMockComponent('RecyclerViewBackedScrollView'),
  RefreshControl: createMockComponent('RefreshControl'),
  SwitchAndroid: createMockComponent('SwitchAndroid'),
  SwitchIOS: createMockComponent('SwitchIOS'),
  TabBarIOS: createMockComponent('TabBarIOS'),
  Text: require('./components/Text'),
  TextInput: require('./components/TextInput'),
  ToastAndroid: createMockComponent('ToastAndroid'),
  ToolbarAndroid: createMockComponent('ToolbarAndroid'),
  Touchable: createMockComponent('Touchable'),
  TouchableHighlight: createMockComponent('TouchableHighlight'),
  TouchableNativeFeedback: createMockComponent('TouchableNativeFeedback'),
  TouchableOpacity: createMockComponent('TouchableOpacity'),
  TouchableWithoutFeedback: createMockComponent('TouchableWithoutFeedback'),
  View: require('./components/View'),
  ViewPagerAndroid: createMockComponent('ViewPagerAndroid'),
  WebView: require('./components/WebView'),

  // APIs
  ActionSheetIOS: require('./api/ActionSheetIOS'),
  Alert: require('./api/Alert'),
  AlertIOS: require('./api/AlertIOS'),
  Animated: require('./api/Animated'),
  AppRegistry: require('./api/AppRegistry'),
  AppState: require('./api/AppState'),
  AppStateIOS: require('./api/AppStateIOS'),
  AsyncStorage: require('./api/AsyncStorage'),
  BackAndroid: require('./api/BackAndroid'),
  CameraRoll: require('./api/CameraRoll'),
  Clipboard: require('./NativeModules/Clipboard'),
  DatePickerAndroid: require('./api/DatePickerAndroid'),
  Dimensions: require('./api/Dimensions'),
  Easing: require('./api/Animated/Easing'),
  ImagePickerIOS: require('./api/ImagePickerIOS'),
  IntentAndroid: require('./api/IntentAndroid'),
  InteractionManager: require('./api/InteractionManager'),
  LayoutAnimation: require('./api/LayoutAnimation'),
  Linking: require('./api/Linking'),
  LinkingIOS: require('./api/LinkingIOS'),
  NetInfo: require('./api/NetInfo'),
  PanResponder: require('./api/PanResponder'),
  PixelRatio: require('./api/PixelRatio'),
  PushNotificationIOS: require('./api/PushNotificationIOS'),
  Settings: require('./api/Settings'),
  StatusBarIOS: require('./api/StatusBarIOS'),
  StyleSheet: require('./api/StyleSheet'),
  TimePickerAndroid: require('./api/TimePickerAndroid'),
  UIManager: require('./NativeModules/UIManager'),
  VibrationIOS: require('./api/VibrationIOS'),

  // Plugins
  DeviceEventEmitter: require('./plugins/DeviceEventEmitter'),
  NativeAppEventEmitter: require('./plugins/NativeAppEventEmitter'),
  NativeModules: require('./NativeModules'),
  Platform: require('./plugins/Platform'),
  processColor: require('./plugins/processColor'),
  requireNativeComponent: require('./plugins/requireNativeComponent'),

  // Prop Types
  ColorPropType: require('./propTypes/ColorPropType'),
  EdgeInsetsPropType: require('./propTypes/EdgeInsetsPropType'),
  PointPropType: require('./propTypes/PointPropType'),
};

// See http://facebook.github.io/react/docs/addons.html
const ReactNativeAddons = {
  LinkedStateMixin: require('react-addons-linked-state-mixin'),
  Perf: require('react-addons-perf'),
  PureRenderMixin: require('react-addons-pure-render-mixin'),
  TestModule: require('./NativeModules/TestModule'),
  TestUtils: require('react-addons-test-utils'),
  // TODO(lmr): not sure where to find this
  // batchedUpdates: require('ReactUpdates').batchedUpdates,
  cloneWithProps: require('react-addons-clone-with-props'),
  createFragment: require('react-addons-create-fragment'),
  update: require('react-addons-update'),
};

Object.assign(ReactNative, React, { addons: ReactNativeAddons });

module.exports = ReactNative;
<|endoftext|>


<commit_before>'use strict';
var fs = require('fs')
var pointer = require('./backend/pointer')
var domutils = require('domutils')
var _ = require('lodash')

var string = '(CS 2222 and CS 23()843) or CS 2343'

var buffer = string.split('')

function parseString(buffer) {

	var numOpenParens = 0;

	var retVal = [];
	while (buffer.length > 0) {
		if (buffer[0].type === 'char') {
			if (buffer[0].value === ')') {
				if (numOpenParens === 0) {
					console.log(buffer[0],'HERE!')
					break;
				}
				else {
					retVal.push(')')
					numOpenParens--
				}
			}
			else if (buffer[0].value == '(') {
				numOpenParens++;
				retVal.push('(')
			}
			else if (bufferStartsWith(buffer,' or ') || bufferStartsWith(buffer,' and ')) {
				break;
			}
			else {
				retVal.push(buffer[0].value)
			}
		}
		else if (buffer[0].type === 'element') {

		}
		else {
			elog(buffer[0])
		}
		buffer.shift()
	}
	return retVal.join('').trim()
}

// parseString('CS 23()843'.split(''))
// process.exit()

function bufferStartsWith(buffer, string) {
	if (buffer.length < string.length) {
		return false;
	}

	for (var i = 0;i<string.length;i++) {
		if (buffer[i].value != string[i]) {
			return false;
		}
	}
	return true;
}

function parse(buffer, stackCount) {
	var retVal = [
		[]
	]

	if (stackCount === undefined) {
		stackCount = 0
	}

	var type = null;

	while (buffer.length > 0) {

		console.log("Parsing:",buffer[0].value || buffer[0],buffer.length)

		if (buffer[0].type === 'char') {

			if (buffer[0].value == '(') {
				buffer.shift()
				console.log('calling and type is ',type)
				retVal[retVal.length - 1] = parse(buffer,stackCount+1)
				console.log('just afte rthe call ',type)
			}
			else if (buffer[0].value === ')') {
				buffer.shift()
				break;
			}
			else if (bufferStartsWith(buffer,' or ') || bufferStartsWith(buffer,' and ')) {

				if (bufferStartsWith(buffer,' or ')) {
					if (type && type!='or') {
						elog('mismatched types? or',type,stackCount,retVal,buffer.slice(0,10))
						process.exit()
					}
					console.log('setting to or',stackCount)
					buffer.splice(0, 4)
					type = 'or'
					retVal.push([])
				}
				else if (bufferStartsWith(buffer,' and ')) {
					if (type && type !='and') {
						elog('mismatched types? and ',type,stackCount)
					}
					console.log('setting to and',stackCount)
					buffer.splice(0, 5)
					type = 'and'
					retVal.push([])
				}
			}
			else {

				var element = parseString(buffer);
				console.log("Parsed: ", element);
				retVal[retVal.length - 1] = element
			}
		}
		else if (buffer[0].type === 'element') {
			if (buffer[0].name === 'br') {
				// buffer.shift();
				if (retVal.length > 1) {
					if (type) {
						elog('mismatched types?')
					}
					console.log('HIIII',retVal)
					type = 'and'
					retVal.push([])
				}
			}
			else if (buffer[0].name == 'a') {
				elog('got a outside of an element??',buffer[0])
			}
			else {
				elog('unknown buffer[0]',buffer[0])
			}
			buffer.shift()
		}
		else {
			elog('unknown buffer[0]',buffer[0])
			buffer.shift()
		}
	}
	console.log("returning",retVal)
	return {
		type: type,
		values: retVal
	};
}

function convertElementListToWideMode (elements) {

	var retVal = []

	elements.forEach(function(element){

		if (element.type == 'text') {
			domutils.getText(element).trim().split('').forEach(function(char){
				retVal.push({
					type:"char",
					value:char
				})
			}.bind(this))
		}
		else if (element.type === 'tag') {
			if (element.name == 'br') {
				retVal.push({
					type:'element',
					name:element.name,
				})
			}
			else if (element.name == 'a') {
				retVal.push({
					type:'element',
					name:element.name,
					href:element.attribs.href
				})
			}
			else {
				elog('Skipping unknown element',element.name)
			}
		}
		else {
			elog('Skipping unknown type:',element.type)
		}
	}.bind(this))

	return retVal;
}

// Class details should be a list of dom elements
// sectionName should be either 'prerequisites' or 'corequisites'
// This function will find all elements in the given section from a part of the dom where the section we are looking for are on the top part
function findRequisitesSection(classDetails, sectionName) {
	var elements = [];
	var i = 0;
	sectionName = sectionName.toLowerCase()

	//skip all elements until the section
	for (; i < classDetails.length; i++) {
		if (classDetails[i].type == 'tag' && _(domutils.getText(classDetails[i]).trim().toLowerCase()).includes(sectionName)) {
			break;
		}
	}
	i++;

	//add all text/elements until next element
	for (; i < classDetails.length; i++) {
		if (classDetails[i].type == 'tag') {
			if (classDetails[i].name == 'br' || classDetails[i].name == 'a') {
				elements.push(classDetails[i])
				continue;
			}
			else {
				break;
			}
		}
		else {
			elements.push(classDetails[i]);
		}
	}

	return elements
}

fs.readFile('../coursepro/backend/parsers/tests/data/ellucianSectionParser/many non linked.html', 'utf8', function (err, body) {
	// expect(err).toBe(null);

	pointer.handleRequestResponce(body, function (err, dom) {
		// expect(err).toBe(null);

		// var url = 'http://test.hostname.com/PROD/';

		// console.log(dom)

		var elements = findRequisitesSection(dom,'prerequisites')

		var a = convertElementListToWideMode(elements)

		console.log(JSON.stringify(parse(a),null,4))

	}.bind(this))
}.bind(this))

// console.log(JSON.stringify(parse(buffer), null, 4));
<commit_msg>"still works"<commit_after>'use strict';
var fs = require('fs')
var pointer = require('./backend/pointer')
var domutils = require('domutils')
var _ = require('lodash')

var string = '(CS 2222 and CS 23()843) or CS 2343'

var buffer = string.split('')

function parseString(buffer) {

	var numOpenParens = 0;

	var retVal = [];
	while (buffer.length > 0) {
		if (buffer[0].type === 'char') {
			if (buffer[0].value === ')') {
				if (numOpenParens === 0) {
					console.log(buffer[0],'HERE!')
					break;
				}
				else {
					retVal.push(')')
					numOpenParens--
				}
			}
			else if (buffer[0].value == '(') {
				numOpenParens++;
				retVal.push('(')
			}
			else if (bufferStartsWith(buffer,' or ') || bufferStartsWith(buffer,' and ')) {
				break;
			}
			else {
				retVal.push(buffer[0].value)
			}
		}
		else if (buffer[0].type === 'element') {

		}
		else {
			elog(buffer[0])
		}
		buffer.shift()
	}
	return retVal.join('').trim()
}

// parseString('CS 23()843'.split(''))
// process.exit()

function bufferStartsWith(buffer, string) {
	if (buffer.length < string.length) {
		return false;
	}

	for (var i = 0;i<string.length;i++) {
		if (buffer[i].value != string[i]) {
			return false;
		}
	}
	return true;
}

function parse(buffer, stackCount) {
	var retVal = []

	if (stackCount === undefined) {
		stackCount = 0
	}

	var type = null;

	while (buffer.length > 0) {

		console.log("Parsing:",buffer[0].value || buffer[0],buffer.length)

		if (buffer[0].type === 'char') {

			if (buffer[0].value == '(') {
				buffer.shift()
				console.log('calling and type is ',type)
				retVal.push(parse(buffer,stackCount+1))
				console.log('just afte rthe call ',type)
			}
			else if (buffer[0].value === ')') {
				buffer.shift()
				break;
			}
			else if (bufferStartsWith(buffer,' or ') || bufferStartsWith(buffer,' and ')) {

				if (bufferStartsWith(buffer,' or ')) {
					if (type && type!='or') {
						elog('mismatched types? or',type,stackCount,retVal,buffer.slice(0,10))
						process.exit()
					}
					console.log('setting to or',stackCount)
					buffer.splice(0, 4)
					type = 'or'
					// retVal.push([])
				}
				else if (bufferStartsWith(buffer,' and ')) {
					if (type && type !='and') {
						elog('mismatched types? and ',type,stackCount)
					}
					console.log('setting to and',stackCount)
					buffer.splice(0, 5)
					type = 'and'
					// retVal.push([])
				}
			}
			else {

				var element = parseString(buffer);
				console.log("Parsed: ", element);
				retVal.push(element)
			}
		}
		else if (buffer[0].type === 'element') {
			if (buffer[0].name === 'br') {
				// buffer.shift();
				if (retVal.length === 0) {
					if (type) {
						elog('mismatched types?')
					}
					console.log('HIIII',retVal)
					type = 'and'
					// retVal.push([])
				}
			}
			else if (buffer[0].name == 'a') {
				elog('got a outside of an element??',buffer[0])
			}
			else {
				elog('unknown buffer[0]',buffer[0])
			}
			buffer.shift()
		}
		else {
			elog('unknown buffer[0]',buffer[0])
			buffer.shift()
		}
	}
	console.log("returning",retVal)
	return {
		type: type,
		values: retVal
	};
}

function convertElementListToWideMode (elements) {

	var retVal = []

	elements.forEach(function(element){

		if (element.type == 'text') {
			domutils.getText(element).trim().split('').forEach(function(char){
				retVal.push({
					type:"char",
					value:char
				})
			}.bind(this))
		}
		else if (element.type === 'tag') {
			if (element.name == 'br') {
				retVal.push({
					type:'element',
					name:element.name,
				})
			}
			else if (element.name == 'a') {
				retVal.push({
					type:'element',
					name:element.name,
					href:element.attribs.href
				})
			}
			else {
				elog('Skipping unknown element',element.name)
			}
		}
		else {
			elog('Skipping unknown type:',element.type)
		}
	}.bind(this))

	return retVal;
}

// Class details should be a list of dom elements
// sectionName should be either 'prerequisites' or 'corequisites'
// This function will find all elements in the given section from a part of the dom where the section we are looking for are on the top part
function findRequisitesSection(classDetails, sectionName) {
	var elements = [];
	var i = 0;
	sectionName = sectionName.toLowerCase()

	//skip all elements until the section
	for (; i < classDetails.length; i++) {
		if (classDetails[i].type == 'tag' && _(domutils.getText(classDetails[i]).trim().toLowerCase()).includes(sectionName)) {
			break;
		}
	}
	i++;

	//add all text/elements until next element
	for (; i < classDetails.length; i++) {
		if (classDetails[i].type == 'tag') {
			if (classDetails[i].name == 'br' || classDetails[i].name == 'a') {
				elements.push(classDetails[i])
				continue;
			}
			else {
				break;
			}
		}
		else {
			elements.push(classDetails[i]);
		}
	}

	return elements
}

fs.readFile('../coursepro/backend/parsers/tests/data/ellucianSectionParser/many non linked.html', 'utf8', function (err, body) {
	// expect(err).toBe(null);

	pointer.handleRequestResponce(body, function (err, dom) {
		// expect(err).toBe(null);

		// var url = 'http://test.hostname.com/PROD/';

		// console.log(dom)

		var elements = findRequisitesSection(dom,'prerequisites')

		var a = convertElementListToWideMode(elements)

		console.log(JSON.stringify(parse(a),null,4))

	}.bind(this))
}.bind(this))

// console.log(JSON.stringify(parse(buffer), null, 4));
<|endoftext|>


<commit_before>import Immutable from 'immutable'

import AppConfiguration from '_/config'
import * as C from '_/constants'
import { actionReducer } from './utils'
import { SortFields } from '_/utils'

const initialState = Immutable.fromJS({
  vms: {},
  pools: {},
  filters: {},
  sort: { ...SortFields.NAME, isAsc: true },

  missedVms: Immutable.Set(),

  vmsPage: 0,
  vmsExpectMorePages: true,

  poolsPage: 0,
  poolsExpectMorePages: true,

  correlationResult: {},
})

const vms = actionReducer(initialState, {
  [C.UPDATE_VMS] (state, {
    payload: {
      keepSubResources,
      vms,
      vmsPage,
      removeVmIds,
      pools,
      poolsPage,
      removePoolIds,
    },
  }) {
    if (vms && vms.length > 0) {
      state = updateVms(state, vms, keepSubResources)
    }

    if (removeVmIds && removeVmIds.length > 0) {
      state = removeVms(state, removeVmIds)
    }

    if (pools && pools.length > 0) {
      state = updatePools(state, pools)
    }

    if (removePoolIds && removePoolIds > 0) {
      state = removePools(state, removePoolIds)
    }

    state = updateVmsCountForPools(state)

    //
    // Since the REST API doesn't give a record count in paginated responses, we have
    // to guess if there is more to fetch.  Assume there is more to fetch if the pages
    // of VMs or Pools fetched/accessed are full.  Only change a page number if it
    // gets bigger because it is possible to (re)fetch pages that have already been
    // fetched.
    //
    const pageSize = AppConfiguration.pageLimit

    const vmsExpectMorePages = state.get('vms').size >= (state.get('vmsPage') * pageSize)
    state = state.set('vmsExpectMorePages', vmsExpectMorePages)
    if (vmsPage && vmsPage > state.get('vmsPage')) {
      state = state.set('vmsPage', vmsPage)
    }

    const poolsExpectMorePages = state.get('pools').size >= (state.get('poolsPage') * pageSize)
    state = state.set('poolsExpectMorePages', poolsExpectMorePages)
    if (poolsPage && poolsPage > state.get('poolsPage')) {
      state = state.set('poolsPage', poolsPage)
    }

    return state
  },

  [C.SET_VM_DISKS] (state, { payload: { vmId, disks } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'disks'], Immutable.fromJS(disks)) // deep immutable
    } else { // fail, if VM not found
      console.error(`vms.setVmDisks() reducer: vmId ${vmId} not found`)
    }
    return state
  },

  [C.UPDATE_VM_DISK] (state, { payload: { vmId, disk } }) {
    if (state.getIn(['vms', vmId])) {
      const existing = state.getIn(['vms', vmId, 'disks']).findEntry(d => d.get('id') === disk.id)
      if (existing) {
        state = state.mergeDeepIn(['vms', vmId, 'disks', existing[0]], Immutable.fromJS(disk))
      }
    }
    return state
  },

  [C.SET_VM_SNAPSHOTS] (state, { payload: { vmId, snapshots } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'snapshots'], Immutable.fromJS(snapshots)) // deep immutable
    }

    console.error(`vms.setVmSnapshots() reducer: vmId ${vmId} not found`)
    return state
  },

  [C.UPDATE_VM_SNAPSHOT] (state, { payload: { vmId, snapshot } }) {
    if (state.getIn(['vms', vmId])) {
      const snapshotForUpdate = state.getIn(['vms', vmId, 'snapshots']).findIndex((s) => s.get('id') === snapshot.id)
      if (snapshotForUpdate > -1) {
        return state.updateIn(['vms', vmId, 'snapshots', snapshotForUpdate], (s) => s
          .set('description', snapshot.description)
          .set('type', snapshot.type)
          .set('status', snapshot.status)
          .set('persistMemoryState', snapshot.persistMemoryState)) // deep immutable
      }
      return state
    }

    console.error(`vms.setVmSnapshots() reducer: vmId ${vmId} not found`)
    return state
  },

  [C.SET_VM_NICS] (state, { payload: { vmId, nics } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'nics'], Immutable.fromJS(nics)) // deep immutable
    } else { // fail, if VM not found
      console.error(`vms.setVmNics() reducer: vmId ${vmId} not found`)
    }
    return state
  },

  [C.SET_VM_SESSIONS] (state, { payload: { vmId, sessions } }) {
    let consoleInUse = false
    for (const i in sessions) {
      if (sessions[i].consoleUser) {
        consoleInUse = true
        break
      }
    }
    state = state.setIn(['vms', vmId, 'sessions'], Immutable.fromJS(sessions))
    return state.setIn(['vms', vmId, 'consoleInUse'], consoleInUse)
  },

  [C.VM_ACTION_IN_PROGRESS] (state, { payload: { vmId, name, started } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'actionInProgress', name], started)
    }
    return state
  },

  [C.POOL_ACTION_IN_PROGRESS] (state, { payload: { poolId, name, started } }) {
    return state.setIn(['pools', poolId, 'vm', 'actionInProgress', name], started)
  },

  [C.FAILED_EXTERNAL_ACTION] (state, { payload: { message, messageDescriptor, type, failedAction } }) {
    if (message && failedAction && failedAction.payload && failedAction.payload.vmId) {
      const vmId = failedAction.payload.vmId
      if (state.getIn(['vms', vmId])) {
        return state.setIn(['vms', vmId, 'lastMessage'], messageDescriptor || message)
      } else {
        console.error(`API reports an error associated to nonexistent VM ${vmId}, error`,
          { message, messageDescriptor, type, failedAction })
      }
    }

    return state
  },

  [C.SET_VM_ACTION_RESULT] (state, { payload: { vmId, correlationId, result } }) {
    if (!vmId) {
      return state.update('correlationResult', results => results.set(correlationId, result))
    }
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'actionResults', correlationId], result)
    }
    return state
  },

  [C.LOGOUT] (state) { // see the config() reducer
    return state.set('vms', Immutable.fromJS({}))
  },

  [C.SET_FILTERS] (state, { payload: { filters } }) { // see the config() reducer
    return state.set('filters', Immutable.fromJS(filters))
  },

  [C.SET_VM_SORT] (state, { payload: { sort } }) { // see the config() reducer
    return state.set('sort', Immutable.fromJS(sort))
  },
})

/**
 * Merge an array of VMs in to the current `vms`, optionally retaining VM sub resources.
 */
function updateVms (state, updatedVms, keepSubResources) {
  const updates = {}

  updatedVms.forEach(vm => {
    const existingVm = state.hasIn(['vms', vm.id]) ? state.getIn(['vms', vm.id]).toJS() : false

    updates[vm.id] = vm
    updates[vm.id].actionResults = (existingVm && existingVm.actionResults) || {}

    if (existingVm && keepSubResources) {
      updates[vm.id] = {
        ...updates[vm.id],
        ...pullVmSubResources(existingVm),
      }
    }
  })

  state = state.mergeIn(['vms'], Immutable.fromJS(updates))

  const vmsIds = Object.keys(updates)
  state = state.set('missedVms', state.get('missedVms').subtract(vmsIds))

  return state
}

/**
 * Pull the VM_FETCH_ADDITIONAL_DEEP values from a vm
 */
function pullVmSubResources (vm) {
  const subResources = {}

  // Only copy consoles if the VM does not already have any
  subResources.consoles = vm.consoles.length === 0 ? vm.consoles || [] : vm.consoles

  subResources.cdrom = vm.cdrom || { file: { id: '' } }
  subResources.disks = vm.disks || []
  subResources.nics = vm.nics || []
  subResources.sessions = vm.sessions || []
  subResources.snapshots = vm.snapshots || []
  subResources.statistics = vm.statistics || []

  subResources.permissions = vm.permissions || []
  subResources.userPermits = vm.userPermits || []
  subResources.canUserChangeCd = !!vm.canUserChangeCd
  subResources.canUserEditVm = !!vm.canUserEditVm
  subResources.canUserManipulateSnapshots = !!vm.canUserManipulateSnapshots
  subResources.canUserEditVmStorage = !!vm.canUserEditVmStorage

  return subResources
}

function removeVms (state, vmIds) {
  const mutable = state.asMutable()
  vmIds.forEach(vmId => mutable.deleteIn(['vms', vmId]))
  mutable.update('missedVms', missedVms => missedVms.union(vmIds))
  return mutable.asImmutable()
}

/**
 * Merge an array of Pools in to the current `pools`.
 */
function updatePools (state, updatedPools) {
  const updates = {}

  updatedPools.forEach(pool => {
    updates[pool.id] = pool
  })

  return state.mergeIn(['pools'], Immutable.fromJS(updates))
}

function removePools (state, poolIds) {
  const mutable = state.asMutable()
  poolIds.forEach(poolId => mutable.deleteIn(['pools', poolId]))
  return mutable.asImmutable()
}

/**
 * Update the `vmsCount` attribute for each Pool based on VM pool ids.
 */
function updateVmsCountForPools (state) {
  state = state.update('pools', pools => pools.map(pool => pool.set('vmsCount', 0)))

  state.get('vms').forEach(vm => {
    const vmPoolId = vm.getIn(['pool', 'id'])
    if (vmPoolId && state.getIn(['pools', vmPoolId])) {
      // VM is in a known pool ... down VMs don't count against the user total unless it is a manual pool
      if (vm.get('status') !== 'down' || state.getIn(['pools', vmPoolId, 'type']) === 'manual') {
        state = state.updateIn(['pools', vmPoolId, 'vmsCount'], count => count + 1)
      }
    }
  })

  return state
}

export default vms
export {
  initialState,
}
<commit_msg>Fix typo preventing pool removal<commit_after>import Immutable from 'immutable'

import AppConfiguration from '_/config'
import * as C from '_/constants'
import { actionReducer } from './utils'
import { SortFields } from '_/utils'

const initialState = Immutable.fromJS({
  vms: {},
  pools: {},
  filters: {},
  sort: { ...SortFields.NAME, isAsc: true },

  missedVms: Immutable.Set(),

  vmsPage: 0,
  vmsExpectMorePages: true,

  poolsPage: 0,
  poolsExpectMorePages: true,

  correlationResult: {},
})

const vms = actionReducer(initialState, {
  [C.UPDATE_VMS] (state, {
    payload: {
      keepSubResources,
      vms,
      vmsPage,
      removeVmIds,
      pools,
      poolsPage,
      removePoolIds,
    },
  }) {
    if (vms && vms.length > 0) {
      state = updateVms(state, vms, keepSubResources)
    }

    if (removeVmIds && removeVmIds.length > 0) {
      state = removeVms(state, removeVmIds)
    }

    if (pools && pools.length > 0) {
      state = updatePools(state, pools)
    }

    if (removePoolIds && removePoolIds.length > 0) {
      state = removePools(state, removePoolIds)
    }

    state = updateVmsCountForPools(state)

    //
    // Since the REST API doesn't give a record count in paginated responses, we have
    // to guess if there is more to fetch.  Assume there is more to fetch if the pages
    // of VMs or Pools fetched/accessed are full.  Only change a page number if it
    // gets bigger because it is possible to (re)fetch pages that have already been
    // fetched.
    //
    const pageSize = AppConfiguration.pageLimit

    const vmsExpectMorePages = state.get('vms').size >= (state.get('vmsPage') * pageSize)
    state = state.set('vmsExpectMorePages', vmsExpectMorePages)
    if (vmsPage && vmsPage > state.get('vmsPage')) {
      state = state.set('vmsPage', vmsPage)
    }

    const poolsExpectMorePages = state.get('pools').size >= (state.get('poolsPage') * pageSize)
    state = state.set('poolsExpectMorePages', poolsExpectMorePages)
    if (poolsPage && poolsPage > state.get('poolsPage')) {
      state = state.set('poolsPage', poolsPage)
    }

    return state
  },

  [C.SET_VM_DISKS] (state, { payload: { vmId, disks } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'disks'], Immutable.fromJS(disks)) // deep immutable
    } else { // fail, if VM not found
      console.error(`vms.setVmDisks() reducer: vmId ${vmId} not found`)
    }
    return state
  },

  [C.UPDATE_VM_DISK] (state, { payload: { vmId, disk } }) {
    if (state.getIn(['vms', vmId])) {
      const existing = state.getIn(['vms', vmId, 'disks']).findEntry(d => d.get('id') === disk.id)
      if (existing) {
        state = state.mergeDeepIn(['vms', vmId, 'disks', existing[0]], Immutable.fromJS(disk))
      }
    }
    return state
  },

  [C.SET_VM_SNAPSHOTS] (state, { payload: { vmId, snapshots } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'snapshots'], Immutable.fromJS(snapshots)) // deep immutable
    }

    console.error(`vms.setVmSnapshots() reducer: vmId ${vmId} not found`)
    return state
  },

  [C.UPDATE_VM_SNAPSHOT] (state, { payload: { vmId, snapshot } }) {
    if (state.getIn(['vms', vmId])) {
      const snapshotForUpdate = state.getIn(['vms', vmId, 'snapshots']).findIndex((s) => s.get('id') === snapshot.id)
      if (snapshotForUpdate > -1) {
        return state.updateIn(['vms', vmId, 'snapshots', snapshotForUpdate], (s) => s
          .set('description', snapshot.description)
          .set('type', snapshot.type)
          .set('status', snapshot.status)
          .set('persistMemoryState', snapshot.persistMemoryState)) // deep immutable
      }
      return state
    }

    console.error(`vms.setVmSnapshots() reducer: vmId ${vmId} not found`)
    return state
  },

  [C.SET_VM_NICS] (state, { payload: { vmId, nics } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'nics'], Immutable.fromJS(nics)) // deep immutable
    } else { // fail, if VM not found
      console.error(`vms.setVmNics() reducer: vmId ${vmId} not found`)
    }
    return state
  },

  [C.SET_VM_SESSIONS] (state, { payload: { vmId, sessions } }) {
    let consoleInUse = false
    for (const i in sessions) {
      if (sessions[i].consoleUser) {
        consoleInUse = true
        break
      }
    }
    state = state.setIn(['vms', vmId, 'sessions'], Immutable.fromJS(sessions))
    return state.setIn(['vms', vmId, 'consoleInUse'], consoleInUse)
  },

  [C.VM_ACTION_IN_PROGRESS] (state, { payload: { vmId, name, started } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'actionInProgress', name], started)
    }
    return state
  },

  [C.POOL_ACTION_IN_PROGRESS] (state, { payload: { poolId, name, started } }) {
    return state.setIn(['pools', poolId, 'vm', 'actionInProgress', name], started)
  },

  [C.FAILED_EXTERNAL_ACTION] (state, { payload: { message, messageDescriptor, type, failedAction } }) {
    if (message && failedAction && failedAction.payload && failedAction.payload.vmId) {
      const vmId = failedAction.payload.vmId
      if (state.getIn(['vms', vmId])) {
        return state.setIn(['vms', vmId, 'lastMessage'], messageDescriptor || message)
      } else {
        console.error(`API reports an error associated to nonexistent VM ${vmId}, error`,
          { message, messageDescriptor, type, failedAction })
      }
    }

    return state
  },

  [C.SET_VM_ACTION_RESULT] (state, { payload: { vmId, correlationId, result } }) {
    if (!vmId) {
      return state.update('correlationResult', results => results.set(correlationId, result))
    }
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'actionResults', correlationId], result)
    }
    return state
  },

  [C.LOGOUT] (state) { // see the config() reducer
    return state.set('vms', Immutable.fromJS({}))
  },

  [C.SET_FILTERS] (state, { payload: { filters } }) { // see the config() reducer
    return state.set('filters', Immutable.fromJS(filters))
  },

  [C.SET_VM_SORT] (state, { payload: { sort } }) { // see the config() reducer
    return state.set('sort', Immutable.fromJS(sort))
  },
})

/**
 * Merge an array of VMs in to the current `vms`, optionally retaining VM sub resources.
 */
function updateVms (state, updatedVms, keepSubResources) {
  const updates = {}

  updatedVms.forEach(vm => {
    const existingVm = state.hasIn(['vms', vm.id]) ? state.getIn(['vms', vm.id]).toJS() : false

    updates[vm.id] = vm
    updates[vm.id].actionResults = (existingVm && existingVm.actionResults) || {}

    if (existingVm && keepSubResources) {
      updates[vm.id] = {
        ...updates[vm.id],
        ...pullVmSubResources(existingVm),
      }
    }
  })

  state = state.mergeIn(['vms'], Immutable.fromJS(updates))

  const vmsIds = Object.keys(updates)
  state = state.set('missedVms', state.get('missedVms').subtract(vmsIds))

  return state
}

/**
 * Pull the VM_FETCH_ADDITIONAL_DEEP values from a vm
 */
function pullVmSubResources (vm) {
  const subResources = {}

  // Only copy consoles if the VM does not already have any
  subResources.consoles = vm.consoles.length === 0 ? vm.consoles || [] : vm.consoles

  subResources.cdrom = vm.cdrom || { file: { id: '' } }
  subResources.disks = vm.disks || []
  subResources.nics = vm.nics || []
  subResources.sessions = vm.sessions || []
  subResources.snapshots = vm.snapshots || []
  subResources.statistics = vm.statistics || []

  subResources.permissions = vm.permissions || []
  subResources.userPermits = vm.userPermits || []
  subResources.canUserChangeCd = !!vm.canUserChangeCd
  subResources.canUserEditVm = !!vm.canUserEditVm
  subResources.canUserManipulateSnapshots = !!vm.canUserManipulateSnapshots
  subResources.canUserEditVmStorage = !!vm.canUserEditVmStorage

  return subResources
}

function removeVms (state, vmIds) {
  const mutable = state.asMutable()
  vmIds.forEach(vmId => mutable.deleteIn(['vms', vmId]))
  mutable.update('missedVms', missedVms => missedVms.union(vmIds))
  return mutable.asImmutable()
}

/**
 * Merge an array of Pools in to the current `pools`.
 */
function updatePools (state, updatedPools) {
  const updates = {}

  updatedPools.forEach(pool => {
    updates[pool.id] = pool
  })

  return state.mergeIn(['pools'], Immutable.fromJS(updates))
}

function removePools (state, poolIds) {
  const mutable = state.asMutable()
  poolIds.forEach(poolId => mutable.deleteIn(['pools', poolId]))
  return mutable.asImmutable()
}

/**
 * Update the `vmsCount` attribute for each Pool based on VM pool ids.
 */
function updateVmsCountForPools (state) {
  state = state.update('pools', pools => pools.map(pool => pool.set('vmsCount', 0)))

  state.get('vms').forEach(vm => {
    const vmPoolId = vm.getIn(['pool', 'id'])
    if (vmPoolId && state.getIn(['pools', vmPoolId])) {
      // VM is in a known pool ... down VMs don't count against the user total unless it is a manual pool
      if (vm.get('status') !== 'down' || state.getIn(['pools', vmPoolId, 'type']) === 'manual') {
        state = state.updateIn(['pools', vmPoolId, 'vmsCount'], count => count + 1)
      }
    }
  })

  return state
}

export default vms
export {
  initialState,
}
<|endoftext|>


<commit_before>import { createStore as _createStore, applyMiddleware, compose } from 'redux';
import createMiddleware from './middleware/clientMiddleware';
import transitionMiddleware from './middleware/transitionMiddleware';

export default function createStore(reduxReactRouter, getRoutes, createHistory, client, data) {
  const middleware = [createMiddleware(client), transitionMiddleware];

  let finalCreateStore;
  if (__DEVELOPMENT__ && __CLIENT__ && __DEVTOOLS__) {
    const { devTools, persistState } = require('redux-devtools');
    finalCreateStore = compose(
      applyMiddleware(...middleware),
      devTools(),
      persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
    )(_createStore);
  } else {
    finalCreateStore = applyMiddleware(...middleware)(_createStore);
  }

  finalCreateStore = reduxReactRouter({ getRoutes, createHistory })(finalCreateStore);

  const reducer = require('./modules/reducer');
  const store = finalCreateStore(reducer, data);
  store.client = client;

  if (__DEVELOPMENT__ && module.hot) {
    module.hot.accept('./modules/reducer', () => {
      store.replaceReducer(require('./modules/reducer'));
    });
  }

  return store;
}
<commit_msg>removed old vestigial design element<commit_after>import { createStore as _createStore, applyMiddleware, compose } from 'redux';
import createMiddleware from './middleware/clientMiddleware';
import transitionMiddleware from './middleware/transitionMiddleware';

export default function createStore(reduxReactRouter, getRoutes, createHistory, client, data) {
  const middleware = [createMiddleware(client), transitionMiddleware];

  let finalCreateStore;
  if (__DEVELOPMENT__ && __CLIENT__ && __DEVTOOLS__) {
    const { devTools, persistState } = require('redux-devtools');
    finalCreateStore = compose(
      applyMiddleware(...middleware),
      devTools(),
      persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
    )(_createStore);
  } else {
    finalCreateStore = applyMiddleware(...middleware)(_createStore);
  }

  finalCreateStore = reduxReactRouter({ getRoutes, createHistory })(finalCreateStore);

  const reducer = require('./modules/reducer');
  const store = finalCreateStore(reducer, data);

  if (__DEVELOPMENT__ && module.hot) {
    module.hot.accept('./modules/reducer', () => {
      store.replaceReducer(require('./modules/reducer'));
    });
  }

  return store;
}
<|endoftext|>


<commit_before>;(function rekapiActor (global) {

  var gk
      ,actorCount
      ,ActorMethods;

  gk = global.Kapi;
  actorCount = 0;

  function getUniqueActorId () {
    return actorCount++;
  }

  //TODO:  Oh noes, this is a linear search!  Maybe optimize it?
  function getCurrentMillisecondRangeIndex (actor, millisecond) {
    var i, len
        ,list;

    list = actor._keyframeList;
    len = list.length;

    for (i = 1; i < len; i++) {
      if (list[i] >= millisecond) {
        return (i - 1);
      }
    }

    return -1;
  }

  gk.Actor = function Actor (kapi, opt_config) {

    opt_config = opt_config || {};

    this.constructor.call(this, {
      'fps': kapi.config.fps
      ,'initialState': opt_config.initialState
    });

    _.extend(this, {
      '_keyframes': {}
      ,'_keyframeList': []
      ,'id': getUniqueActorId()
      ,'kapi': kapi
      ,'setup': opt_config.setup || gk.noop
      ,'draw': opt_config.draw || gk.noop
      ,'teardown': opt_config.teardown || gk.noop
    });

    return this;
  };

  ActorMethods = function () {};
  ActorMethods.prototype = Tweenable.prototype;
  gk.Actor.prototype = new ActorMethods();

  /**
   * @param {number} when
   * @param {Object} position
   */
  gk.Actor.prototype.keyframe = function keyframe (when, position) {
    this._keyframes[when] = position;
    this._keyframeList.push(when);
    gk.util.sortNumerically(this._keyframeList);
    this.kapi.updateInternalState();

    return this;
  };

  gk.Actor.prototype.calculatePosition = function (forMillisecond) {
    var keyframeList
        ,keyframes
        ,delta
        ,interpolatedPosition
        ,startMs
        ,endMs
        ,timeRangeIndexStart
        ,rangeFloor
        ,rangeCeil;

    keyframeList = this._keyframeList;
    startMs = _.first(keyframeList);
    endMs = _.last(keyframeList);

    if (startMs <= forMillisecond && forMillisecond <= endMs) {

      keyframes = this._keyframes;
      timeRangeIndexStart = getCurrentMillisecondRangeIndex(this,
          forMillisecond);
      rangeFloor = keyframeList[timeRangeIndexStart];
      rangeCeil = keyframeList[timeRangeIndexStart + 1];
      delta = rangeCeil - rangeFloor;
      interpolatedPosition = (forMillisecond - rangeFloor) / delta;

      this
        .set(keyframes[keyframeList[timeRangeIndexStart]])
        .interpolate(keyframes[keyframeList[timeRangeIndexStart + 1]],
            interpolatedPosition);

    } else {
      this.set({});
    }

  };

} (this));<commit_msg>Some fun code comments.<commit_after>;(function rekapiActor (global) {

  var gk
      ,actorCount
      ,ActorMethods;

  gk = global.Kapi;
  actorCount = 0;

  function getUniqueActorId () {
    return actorCount++;
  }

  //TODO:  Oh noes, this is a linear search!  Maybe optimize it?
  function getCurrentMillisecondRangeIndex (actor, millisecond) {
    var i, len
        ,list;

    list = actor._keyframeList;
    len = list.length;

    for (i = 1; i < len; i++) {
      if (list[i] >= millisecond) {
        return (i - 1);
      }
    }

    return -1;
  }

  gk.Actor = function Actor (kapi, opt_config) {

    opt_config = opt_config || {};

    // Steal the `Tweenable` constructor.
    this.constructor.call(this, {
      'fps': kapi.config.fps
      ,'initialState': opt_config.initialState
    });

    _.extend(this, {
      '_keyframes': {}
      ,'_keyframeList': []
      ,'id': getUniqueActorId()
      ,'kapi': kapi
      ,'setup': opt_config.setup || gk.noop
      ,'draw': opt_config.draw || gk.noop
      ,'teardown': opt_config.teardown || gk.noop
    });

    return this;
  };

  // Kind of a fun way to set up an inheritance chain.  `ActorMethods` prevents
  // methods on `Actor.prototype` from polluting `Tweenable`'s prototype with
  // `Actor` specific methods.
  ActorMethods = function () {};
  ActorMethods.prototype = Tweenable.prototype;
  gk.Actor.prototype = new ActorMethods();
  // But the magic doesn't stop here!  `Actor`'s constructor steals the
  // `Tweenable` constuctor.

  /**
   * @param {number} when
   * @param {Object} position
   */
  gk.Actor.prototype.keyframe = function keyframe (when, position) {
    this._keyframes[when] = position;
    this._keyframeList.push(when);
    gk.util.sortNumerically(this._keyframeList);
    this.kapi.updateInternalState();

    return this;
  };

  gk.Actor.prototype.calculatePosition = function (forMillisecond) {
    var keyframeList
        ,keyframes
        ,delta
        ,interpolatedPosition
        ,startMs
        ,endMs
        ,timeRangeIndexStart
        ,rangeFloor
        ,rangeCeil;

    keyframeList = this._keyframeList;
    startMs = _.first(keyframeList);
    endMs = _.last(keyframeList);

    if (startMs <= forMillisecond && forMillisecond <= endMs) {

      keyframes = this._keyframes;
      timeRangeIndexStart = getCurrentMillisecondRangeIndex(this,
          forMillisecond);
      rangeFloor = keyframeList[timeRangeIndexStart];
      rangeCeil = keyframeList[timeRangeIndexStart + 1];
      delta = rangeCeil - rangeFloor;
      interpolatedPosition = (forMillisecond - rangeFloor) / delta;

      this
        .set(keyframes[keyframeList[timeRangeIndexStart]])
        .interpolate(keyframes[keyframeList[timeRangeIndexStart + 1]],
            interpolatedPosition);

    } else {
      this.set({});
    }

  };

} (this));<|endoftext|>


<commit_before>var xs = [];

var prev = convert(0);
for (var n = 1; true; n++) {
    var cur = convert(n);
    if (cur <= prev) break;
    prev = cur;
}
console.log(n - 1);

function convert (n) {
    var bytes;
    var x = n - 252;
    if (n < 252) {
        bytes = [ n ];
    }
    else if (x < 256) {
        bytes = [ 252, x ];
    }
    else if (x < 256*256) {
        bytes = [ 253, Math.floor(x / 256), x % 256 ];
    }
    else if (x < 256*256*256) {
        bytes = [
            254,
            Math.floor(x / 256 / 256),
            Math.floor(x / 256) % 256,
            x % 256
        ];
    }
    else if (x < 256*256*256*256) {
        bytes = [
            255,
            Math.floor(x / 256 / 256 / 256),
            Math.floor(x / 256 / 256) % 256,
            Math.floor(x / 256) % 256,
            x % 256
        ];
    }
    return Buffer(bytes).toString('hex');
}
<commit_msg>fix the >4 billion base case<commit_after>var convert = require('./');

var prev = convert(0);
var skip = 1;
for (var n = 1; n < Number.MAX_VALUE; n += skip) {
    var cur = convert(n, 'hex');
    if (cur <= prev) break;
    prev = cur;
    console.log(n, cur);
    if (n > 256*256) {
        skip = 1 + Math.pow(245, Math.ceil(Math.log(n) / Math.log(256)));
    }
}
console.log(n - 1);
<|endoftext|>


<commit_before>//Application Frame v0.1.0 - copyright by TitanNano / Jovan Ggerodetti - http://www.titannano.de

(function(){

this.self= this, "use strict";

//default settings for the Application Frame Engine
var settings= {
//  the coreLock option locks the settings and prevents from overwriteing
//  the coreLock is disabled for default
    coreLock : false,
//  the masterApplication option defines the name of the app which should get master privileges.
//  for default no app name is set.
    masterApplication : null,
//  the render mode defines how to handle the different tasks.
//  default means all apps and services running in the main thread.
	renderMode : 'default',
//  turn on preprocessing, to use Application Frame specific syntax.
	preProcessing : false,
//  if turned on, only one application can be runned at once.
    singleApplicationMode : false,
//  when enabled the engine checks if the runtime environment supports all required APIs.
//  If any dependencies couldn't be found, the user will be forwarded to crashPage.
	support : true,
//  defines the page to which the engine forwards, if there is a unsolved dependency.
	crashPage : 'about:blank',
// gives the main application the possibility to access the engine object (only available in node)
    grantRoot : false
	};

// Classes
// this class defines a new application scope
var ApplicationScope= function(name){
	var thisScope= this;
	this.name= name;
	this.type= 'application';
	this.settings= {
		allowSetters : true,
		allowGetters : true,
		lockOverride : false,
		autoLock : true
        };
	this.properties=  {
        addSetterListener : function(key, callback){
			thisScope.setterListeners.push({key : key, callback : callback});
			}
        };
	this.thread= null;
	this.worker= null;
	this.setterListeners= [];
    this.override= function(newSettings){
        if(!thisScope.settings.lockOverride){
            for(var i in newSettings)
                if(thisScope.settings[i]) thisScope.settings[i]= newSettings[i];
            if(!newSettings.hasOwnProperty('lockOverride') && thisScope.settings.autoLock) thisScope.settings.lockOverride= true;
            }
        };
	};

var MozillaAddonScope = function(){
    var thisScope= this;
    this.name= "addon";
    this.type= 'addon';
    this.settings= {
        sdkPrefix : false,
        contentPrefixChar : '*',
        contentPrefix : false,
        fastExport : true
        };
    this.defaultProperties= {
        };
    this.modules= {};
    this.global= null;
    this.thread= null;
    this.override= function(newSettings){
        for(var i in newSettings)
            if(thisScope.settings[i]) thisScope.settings[i]= newSettings[i];
        };
    };

var scopes= [];

//all selectable items for the $ selector.
var items= {
	application : {
		'new' : function(name){
			var exists= false;
			scopes.forEach(function(item){
				if(item.name == name) exists= true;
				});

			if(!exists && !engine.isApplicationLimit){
				scopes.push(new ApplicationScope(name));
                if(scopes.length < 1) engine.mainApplication= scopes[scopes.length-1];
				if(settings.singleApplicationMode) engine.isApplicationLimit= true;
                if(settings.masterApplication == scopes[scopes.length-1].name)
                    engine.mainApplication= scopes[scopes.length-1];
			}else{
				throw "application \""+name+"\" already exists!!";
				}
			}
		},
    'new' : function(settings){
        var object = {};
        if(settings.constructor){
            object= new settings.constructor(engine);
        }else if(settings.builder && settings.nameSpace){
            engine[settings.nameSpace]= {};
            object= function(){
				return settings.builder(engine[settings.nameSpace], this.arguments);
			};
        }else if(settings.builder){
            object= settings.builder;
        }else{
            object= settings.object;
        }

        if(settings.name && !items[settings.name])
            items[settings.name]= object;
        else
            self.console.error("No or ilegall name!");
        if(settings._init){
            if(settings.nameSpace)
                settings._init(engine[settings.nameSpace], settings.object);
            else
                settings._init(settings.object);
            }
        if(settings.nameSpace)
            return engine[settings.nameSpace];
        return null;
        },
    queue : {
        push : function(object){
            var push= function(){
                this.count++;
                if(this.type.length && this.count == this.type.length){
                    this.action();
                    engine.launchQueue.splice(engine.launchQueue.indexOf(this), 1);
                }else if(!this.type.length){
                    this.action();
                    engine.launchQueue.splice(engine.launchQueue.indexOf(this), 1);
                }
            };

            if(typeof object == 'object'){
                object.push= push;
                engine.launchQueue.push(object);
                return true;
            }else self.console.error('The launch queue only accepts launch objects!');
        },
        trigger : function(type){
            engine.launchQueue.forEach(function(i){
                if(i.type == type) i.push();
            });
        }
    },
    dom : {
        select : function(query){
            return self.document.querySelector(query);
        },
        selectAll : function(query){
            return self.document.querySelectorAll(query);
        },
        append : function(element, target){
            target.appendChild(element);
        },
        create : function(elementName){
            return self.document.createElement(elementName);
        },
        enrtyPoint : function(entryPoint){
            return {
                select : function(query){
                    entryPoint.querySelector(query);
                },
                selectAll : function(query){
                    entryPoint.querySelectorAll(query);
                }
            };
        }
    },
    escape : {
        wrapper : function(sub){
            if(sub())
                return true;
            else
                return false;
        }
    },
};

//selects a item of the items hash.
var selector= function(name){
	if(items[name])
		return items[name];
	else
		self.console.error('unknown selector!!');
	};

var handleEvents= function(scope, key){
    scope.setterListeners.forEach(function(item){
        if(item.key == key)
        item.callback(scope.properties[key]);
    });
};

var findScope= function(name){
    for(var i=0; i < scopes.length; i++){
        if(scopes[i].name == name)
            return scopes[i];
        else
            return null;
    }
};

var prepareScope= function(item){
    if(item){
//      return a application scope
        if(item.type == 'application'){
            var scope= item;
            return {
                main : function(thread){
                    scope.thread= (settings.preProcessing) ? preProcesse(thread) : thread;
                    if(scope.settings.autoLock) scope.settings.isLocked= true;
                    engine.threadQueue.push(scope);
                },
                get : function(name){
                    if(scope.settings.allowGetters && scope.properties[name]){
                        handleEvents(scope, name);
                        return scope.properties[name];
                    }else{
                        return null;
                    }
                },
                set : function(name, value){
                    if(scope.settings.allowSetters && scope.properties[name]){
                        scope.properties[name]= value;
                        handleEvents(scope, name);
                        return true;
                    }else{
                        return false;
                    }
                },
                override : scope.override
            };

        }else if(item.type == 'addon'){
//          return a addon scope (at the moment only mozilla)
            var scope= item;
            return {
                create : function(thread){
                    scope.thread= thread;
                    engine.threadQueue.push(scope);
                },
                'module' : function(f){
                    f.apply(scope.global.exports);
                },
                modules : function(depsObject){
                    for (var i in depsObject){
                        if(!scope.modules[i])
                            scope.modules[i]= depsObject[i];
                    }
                },
                hook : function(globalObject){
                    scope.global= globalObject;
                },
                dataURL : function(name){
                    return self.require('sdk/self').data.url(name);
                }
            };
        }
    }else{
        return null;
    }
};

//the scope selector selects an application or service from the scopes array.
var scopeSelector = function(name){

//  special handling for the application key
	if(name == 'application'){
        if(engine.mainApplication){
            name= engine.mainApplication.name;
            return prepareScope(engine.mainApplication);
        }else{
            throw 'Can not access "application"! No main application is set!';
        }

//  special handling for the eninge key
	}else if(name == 'engine'){
		return {
			override : function(newSettings){
				if(!settings.coreLock){
						for(var i in newSettings){
                            if(settings[i] !== undefined) settings[i]= newSettings[i];
						}
					}
				},
			stop : function(){
				self.location.replace(settings.crashPage);
				},
            requestRoot : function(scope){
                if( (engine.type == 'Node') && (scope == engine.mainApplication.properties) ){
                    scope.engine= engine;
                    return true;
                }else{
                    return false;
                    }
                }
			};
    }else if(engine.type == 'MozillaAddonSDK' && findScope('addon').modules[name]){
        return findScope('addon').modules[name];
	}else{
//      default handling for all other keys
        return prepareScope(findScope(name));
    }
};

//preprocesses source from any function.
var preProcesse= function(func){
	func= func.toString();
	func= func.substring(func.indexOf('{')+1, func.lastIndexOf('}'));

	return new Function(func);
	};

// Engine
//the engine hash, holds private flags, arrays and functions.
var engine = {
	isApplicationLimit : false,
	mainApplication : null,
	name : 'unknown',
    version : '1',
    platform : 'unknown',
    arch : 'x32',
    type : 'Web',
	activeThreads : 0,
	domUpdates : [],
	threadQueue : {
		queue : [],
		push : function(scope){
			if(!this.isRunning){
				this.isRunning= true;
				if(settings.renderMode == 'default'){
					scope.thread.apply(scope.properties, [scope]);
					}

				if(this.queue.length > 0){
					var n= this.queue[0]; this.queue.shift();
					this.push(n);
				}
				this.isRunning= false;
			}else{
				this.queue.push(scope);
            }
        },
		isRunning : false
		},
    launchQueue : [],
    exit : function(){}
	};

// get the current Platform
var platform= null;

// find out which engine is used
if (self.navigator){
    platform= self.navigator.userAgent;
//              Mozilla
    platform=   (((platform.indexOf('Gecko/') > -1) && 'Gecko '+platform.substring(platform.indexOf('rv:')+3, platform.indexOf(')')) ) || false) ||
//              Google / Apple / Opera
                (((platform.indexOf('AppleWebKit') > -1) && platform.substring(platform.indexOf('AppleWebKit'), platform.lastIndexOf('(')-1).replace(/\//, ' ')) || false) ||
//              Microsoft
                (((platform.indexOf('Trident/') > -1) && platform.substring(platform.indexOf('Trident/'), platform.indexOf(';', platform.indexOf('Trident/'))).replace(/\//, ' ')) || false) ||
//              Unknown
                'unknown platform';
    platform= platform.split(' ');
    platform.push('Web');

// check if current platform is the Mozilla Add-on runtime
}else if(self.exports && self.require && self.module){
    var system= self.require('sdk/system');
    platform= [system.name, system.version, 'MozillaAddonSDK'];

// check if current platform is the Node.js runtime
}else if(self.process && self.process.versions && self.process.env && self.process.pid){
    platform= ['Node.js', self.process.versions.node, 'Node'];
    }

//  set platform type
engine.type= platform[2];

// various platform tests for the different platforms

/*
Tests for Web platforms.
If any test fails Application Frame will quit but at the moment only a notification in the console will be shown.
*/
if(platform[2] == 'Web'){
    var platformTests= {
        storrage : (self.sessionStorage && self.localStorage),
        indexedDB : (self.indexedDB),
        notifications : (self.Notification),
        renderFrame : (self.requestAnimationFrame),
        audio : (self.Audio),
        indexOf : (self.Array.indexOf),
        forEach : (self.Array.forEach),
        geolocation : (self.navigator.geolocation),
        appCache : (self.applicationCache),
        xcom : (self.postMessage),
        blobs : (self.Blob),
        clipBoard : (self.ClipboardEvent),
        file : (self.File),
        fileReader : (self.FileReader),
        hashchange : (typeof self.onhashchange != "undefined"),
        json : (self.JSON),
        matchMedia : (self.matchMedia),
        timing : (self.PerformanceTiming),
        pageVisibility : ((typeof self.document.hidden != "undefined") && self.document.visibilityState),
        serverSentEvent : (self.EventSource),
        webWorker : (self.Worker),
//        sharedWebWorker : (self.SharedWorker), <--- disabled because it isn't really supported in any web engine
        arrayBuffer : (self.ArrayBuffer),
        webSocket : (self.WebSocket),
        computedStyle : (self.getComputedStyle),
        deviceOrientation : (self.DeviceOrientationEvent),
//        spread : (function(){try{ return eval("var x; x= [1, 2, 3], (function(x, y, z){})(...x), true;"); }catch(e){ return false; }})()
    };

// Tests for the Mozilla Add-on SDK
}else if(platform[2] == 'MozillaAddonSDK'){
//  at the moment there are no known platform tests for the 'Mozilla Add-on SDK' platform.
    var platformTests= {};

// Tests for the Node.js runtime or something like that
}else if(platform[2] == 'Node'){
//  at the moment there are no known platform tests for the 'Node' platform.
    var platformTests= {};
    }

//check if any test failed
var faildTests= 0;
var allTests= 0;
for(var i in platformTests){
    allTests++;
    if(!platformTests[i]){
        faildTests++;
        self.console.log("Test for '"+i+"' faild!!");
        }
}

//if a test failed the engine will quit
if(faildTests > 0){
    self.console.log(faildTests+' of '+allTests+' platform tests are faild!');
//    engine.exit(0);
}

// setup environment
if(platform[2] == 'Web'){
//  check if touchscreen is supported
    self.navigator.isTouch= 'ontouchstart' in self;
    engine.name= platform[0];
    engine.version= platform[1];
    engine.platform= self.navigator.userAgent.substring(self.navigator.userAgent.indexOf('(')+1, self.navigator.userAgent.indexOf(';'));
    engine.arch= self.navigator.userAgent.substring(self.navigator.userAgent.indexOf(';')+2, self.navigator.userAgent.indexOf(';', self.navigator.userAgent.indexOf(';')+1));

//  publish APIs
    self.$= selector;
    self.$_= scopeSelector;

}else if(platform[2] == 'MozillaAddonSDK'){
//  create new Addon Scope
    scopes.push(new MozillaAddonScope());
    engine.name= platform[0];
    engine.version= platform[1];
    engine.platform= platform[2];
//    self.require('af/addonCore.js'); // <--- does not exist yet. Not sure if it is really needed

//  publish APIs
    self.exports.$= selector;
    self.exports.$_= scopeSelector;

}else if(platform[2] == 'Node'){
    engine.name= platform[0];
    engine.version= platform[1];
    engine.platform= self.process.platform;
    engine.arch= self.process.arch;

//  publish APIs
    self.$= selector;
    self.$_= scopeSelector;
}

})();<commit_msg>typing mistake correction<commit_after>//Application Frame v0.1.0 - copyright by TitanNano / Jovan Ggerodetti - http://www.titannano.de

(function(){

this.self= this, "use strict";

//default settings for the Application Frame Engine
var settings= {
//  the coreLock option locks the settings and prevents from overwriteing
//  the coreLock is disabled for default
    coreLock : false,
//  the masterApplication option defines the name of the app which should get master privileges.
//  for default no app name is set.
    masterApplication : null,
//  the render mode defines how to handle the different tasks.
//  default means all apps and services running in the main thread.
	renderMode : 'default',
//  turn on preprocessing, to use Application Frame specific syntax.
	preProcessing : false,
//  if turned on, only one application can be runned at once.
    singleApplicationMode : false,
//  when enabled the engine checks if the runtime environment supports all required APIs.
//  If any dependencies couldn't be found, the user will be forwarded to crashPage.
	support : true,
//  defines the page to which the engine forwards, if there is a unsolved dependency.
	crashPage : 'about:blank',
// gives the main application the possibility to access the engine object (only available in node)
    grantRoot : false
	};

// Classes
// this class defines a new application scope
var ApplicationScope= function(name){
	var thisScope= this;
	this.name= name;
	this.type= 'application';
	this.settings= {
		allowSetters : true,
		allowGetters : true,
		lockOverride : false,
		autoLock : true
        };
	this.properties=  {
        addSetterListener : function(key, callback){
			thisScope.setterListeners.push({key : key, callback : callback});
			}
        };
	this.thread= null;
	this.worker= null;
	this.setterListeners= [];
    this.override= function(newSettings){
        if(!thisScope.settings.lockOverride){
            for(var i in newSettings)
                if(thisScope.settings[i]) thisScope.settings[i]= newSettings[i];
            if(!newSettings.hasOwnProperty('lockOverride') && thisScope.settings.autoLock) thisScope.settings.lockOverride= true;
            }
        };
	};

var MozillaAddonScope = function(){
    var thisScope= this;
    this.name= "addon";
    this.type= 'addon';
    this.settings= {
        sdkPrefix : false,
        contentPrefixChar : '*',
        contentPrefix : false,
        fastExport : true
        };
    this.defaultProperties= {
        };
    this.modules= {};
    this.global= null;
    this.thread= null;
    this.override= function(newSettings){
        for(var i in newSettings)
            if(thisScope.settings[i]) thisScope.settings[i]= newSettings[i];
        };
    };

var scopes= [];

//all selectable items for the $ selector.
var items= {
	application : {
		'new' : function(name){
			var exists= false;
			scopes.forEach(function(item){
				if(item.name == name) exists= true;
				});

			if(!exists && !engine.isApplicationLimit){
				scopes.push(new ApplicationScope(name));
                if(scopes.length < 1) engine.mainApplication= scopes[scopes.length-1];
				if(settings.singleApplicationMode) engine.isApplicationLimit= true;
                if(settings.masterApplication == scopes[scopes.length-1].name)
                    engine.mainApplication= scopes[scopes.length-1];
			}else{
				throw "application \""+name+"\" already exists!!";
				}
			}
		},
    'new' : function(settings){
        var object = {};
        if(settings.constructor){
            object= new settings.constructor(engine);
        }else if(settings.builder && settings.nameSpace){
            engine[settings.nameSpace]= {};
            object= function(){
				return settings.builder(engine[settings.nameSpace], this.arguments);
			};
        }else if(settings.builder){
            object= settings.builder;
        }else{
            object= settings.object;
        }

        if(settings.name && !items[settings.name])
            items[settings.name]= object;
        else
            self.console.error("No or ilegall name!");
        if(settings._init){
            if(settings.nameSpace)
                settings._init(engine[settings.nameSpace], settings.object);
            else
                settings._init(settings.object);
            }
        if(settings.nameSpace)
            return engine[settings.nameSpace];
        return null;
        },
    queue : {
        push : function(object){
            var push= function(){
                this.count++;
                if(this.type.length && this.count == this.type.length){
                    this.action();
                    engine.launchQueue.splice(engine.launchQueue.indexOf(this), 1);
                }else if(!this.type.length){
                    this.action();
                    engine.launchQueue.splice(engine.launchQueue.indexOf(this), 1);
                }
            };

            if(typeof object == 'object'){
                object.push= push;
                engine.launchQueue.push(object);
                return true;
            }else self.console.error('The launch queue only accepts launch objects!');
        },
        trigger : function(type){
            engine.launchQueue.forEach(function(i){
                if(i.type == type) i.push();
            });
        }
    },
    dom : {
        select : function(query){
            return self.document.querySelector(query);
        },
        selectAll : function(query){
            return self.document.querySelectorAll(query);
        },
        append : function(element, target){
            target.appendChild(element);
        },
        create : function(elementName){
            return self.document.createElement(elementName);
        },
        entryPoint : function(entryPoint){
            return {
                select : function(query){
                    entryPoint.querySelector(query);
                },
                selectAll : function(query){
                    entryPoint.querySelectorAll(query);
                }
            };
        }
    },
    escape : {
        wrapper : function(sub){
            if(sub())
                return true;
            else
                return false;
        }
    },
};

//selects a item of the items hash.
var selector= function(name){
	if(items[name])
		return items[name];
	else
		self.console.error('unknown selector!!');
	};

var handleEvents= function(scope, key){
    scope.setterListeners.forEach(function(item){
        if(item.key == key)
        item.callback(scope.properties[key]);
    });
};

var findScope= function(name){
    for(var i=0; i < scopes.length; i++){
        if(scopes[i].name == name)
            return scopes[i];
        else
            return null;
    }
};

var prepareScope= function(item){
    if(item){
//      return a application scope
        if(item.type == 'application'){
            var scope= item;
            return {
                main : function(thread){
                    scope.thread= (settings.preProcessing) ? preProcesse(thread) : thread;
                    if(scope.settings.autoLock) scope.settings.isLocked= true;
                    engine.threadQueue.push(scope);
                },
                get : function(name){
                    if(scope.settings.allowGetters && scope.properties[name]){
                        handleEvents(scope, name);
                        return scope.properties[name];
                    }else{
                        return null;
                    }
                },
                set : function(name, value){
                    if(scope.settings.allowSetters && scope.properties[name]){
                        scope.properties[name]= value;
                        handleEvents(scope, name);
                        return true;
                    }else{
                        return false;
                    }
                },
                override : scope.override
            };

        }else if(item.type == 'addon'){
//          return a addon scope (at the moment only mozilla)
            var scope= item;
            return {
                create : function(thread){
                    scope.thread= thread;
                    engine.threadQueue.push(scope);
                },
                'module' : function(f){
                    f.apply(scope.global.exports);
                },
                modules : function(depsObject){
                    for (var i in depsObject){
                        if(!scope.modules[i])
                            scope.modules[i]= depsObject[i];
                    }
                },
                hook : function(globalObject){
                    scope.global= globalObject;
                },
                dataURL : function(name){
                    return self.require('sdk/self').data.url(name);
                }
            };
        }
    }else{
        return null;
    }
};

//the scope selector selects an application or service from the scopes array.
var scopeSelector = function(name){

//  special handling for the application key
	if(name == 'application'){
        if(engine.mainApplication){
            name= engine.mainApplication.name;
            return prepareScope(engine.mainApplication);
        }else{
            throw 'Can not access "application"! No main application is set!';
        }

//  special handling for the eninge key
	}else if(name == 'engine'){
		return {
			override : function(newSettings){
				if(!settings.coreLock){
						for(var i in newSettings){
                            if(settings[i] !== undefined) settings[i]= newSettings[i];
						}
					}
				},
			stop : function(){
				self.location.replace(settings.crashPage);
				},
            requestRoot : function(scope){
                if( (engine.type == 'Node') && (scope == engine.mainApplication.properties) ){
                    scope.engine= engine;
                    return true;
                }else{
                    return false;
                    }
                }
			};
    }else if(engine.type == 'MozillaAddonSDK' && findScope('addon').modules[name]){
        return findScope('addon').modules[name];
	}else{
//      default handling for all other keys
        return prepareScope(findScope(name));
    }
};

//preprocesses source from any function.
var preProcesse= function(func){
	func= func.toString();
	func= func.substring(func.indexOf('{')+1, func.lastIndexOf('}'));

	return new Function(func);
	};

// Engine
//the engine hash, holds private flags, arrays and functions.
var engine = {
	isApplicationLimit : false,
	mainApplication : null,
	name : 'unknown',
    version : '1',
    platform : 'unknown',
    arch : 'x32',
    type : 'Web',
	activeThreads : 0,
	domUpdates : [],
	threadQueue : {
		queue : [],
		push : function(scope){
			if(!this.isRunning){
				this.isRunning= true;
				if(settings.renderMode == 'default'){
					scope.thread.apply(scope.properties, [scope]);
					}

				if(this.queue.length > 0){
					var n= this.queue[0]; this.queue.shift();
					this.push(n);
				}
				this.isRunning= false;
			}else{
				this.queue.push(scope);
            }
        },
		isRunning : false
		},
    launchQueue : [],
    exit : function(){}
	};

// get the current Platform
var platform= null;

// find out which engine is used
if (self.navigator){
    platform= self.navigator.userAgent;
//              Mozilla
    platform=   (((platform.indexOf('Gecko/') > -1) && 'Gecko '+platform.substring(platform.indexOf('rv:')+3, platform.indexOf(')')) ) || false) ||
//              Google / Apple / Opera
                (((platform.indexOf('AppleWebKit') > -1) && platform.substring(platform.indexOf('AppleWebKit'), platform.lastIndexOf('(')-1).replace(/\//, ' ')) || false) ||
//              Microsoft
                (((platform.indexOf('Trident/') > -1) && platform.substring(platform.indexOf('Trident/'), platform.indexOf(';', platform.indexOf('Trident/'))).replace(/\//, ' ')) || false) ||
//              Unknown
                'unknown platform';
    platform= platform.split(' ');
    platform.push('Web');

// check if current platform is the Mozilla Add-on runtime
}else if(self.exports && self.require && self.module){
    var system= self.require('sdk/system');
    platform= [system.name, system.version, 'MozillaAddonSDK'];

// check if current platform is the Node.js runtime
}else if(self.process && self.process.versions && self.process.env && self.process.pid){
    platform= ['Node.js', self.process.versions.node, 'Node'];
    }

//  set platform type
engine.type= platform[2];

// various platform tests for the different platforms

/*
Tests for Web platforms.
If any test fails Application Frame will quit but at the moment only a notification in the console will be shown.
*/
if(platform[2] == 'Web'){
    var platformTests= {
        storrage : (self.sessionStorage && self.localStorage),
        indexedDB : (self.indexedDB),
        notifications : (self.Notification),
        renderFrame : (self.requestAnimationFrame),
        audio : (self.Audio),
        indexOf : (self.Array.indexOf),
        forEach : (self.Array.forEach),
        geolocation : (self.navigator.geolocation),
        appCache : (self.applicationCache),
        xcom : (self.postMessage),
        blobs : (self.Blob),
        clipBoard : (self.ClipboardEvent),
        file : (self.File),
        fileReader : (self.FileReader),
        hashchange : (typeof self.onhashchange != "undefined"),
        json : (self.JSON),
        matchMedia : (self.matchMedia),
        timing : (self.PerformanceTiming),
        pageVisibility : ((typeof self.document.hidden != "undefined") && self.document.visibilityState),
        serverSentEvent : (self.EventSource),
        webWorker : (self.Worker),
//        sharedWebWorker : (self.SharedWorker), <--- disabled because it isn't really supported in any web engine
        arrayBuffer : (self.ArrayBuffer),
        webSocket : (self.WebSocket),
        computedStyle : (self.getComputedStyle),
        deviceOrientation : (self.DeviceOrientationEvent),
//        spread : (function(){try{ return eval("var x; x= [1, 2, 3], (function(x, y, z){})(...x), true;"); }catch(e){ return false; }})()
    };

// Tests for the Mozilla Add-on SDK
}else if(platform[2] == 'MozillaAddonSDK'){
//  at the moment there are no known platform tests for the 'Mozilla Add-on SDK' platform.
    var platformTests= {};

// Tests for the Node.js runtime or something like that
}else if(platform[2] == 'Node'){
//  at the moment there are no known platform tests for the 'Node' platform.
    var platformTests= {};
    }

//check if any test failed
var faildTests= 0;
var allTests= 0;
for(var i in platformTests){
    allTests++;
    if(!platformTests[i]){
        faildTests++;
        self.console.log("Test for '"+i+"' faild!!");
        }
}

//if a test failed the engine will quit
if(faildTests > 0){
    self.console.log(faildTests+' of '+allTests+' platform tests are faild!');
//    engine.exit(0);
}

// setup environment
if(platform[2] == 'Web'){
//  check if touchscreen is supported
    self.navigator.isTouch= 'ontouchstart' in self;
    engine.name= platform[0];
    engine.version= platform[1];
    engine.platform= self.navigator.userAgent.substring(self.navigator.userAgent.indexOf('(')+1, self.navigator.userAgent.indexOf(';'));
    engine.arch= self.navigator.userAgent.substring(self.navigator.userAgent.indexOf(';')+2, self.navigator.userAgent.indexOf(';', self.navigator.userAgent.indexOf(';')+1));

//  publish APIs
    self.$= selector;
    self.$_= scopeSelector;

}else if(platform[2] == 'MozillaAddonSDK'){
//  create new Addon Scope
    scopes.push(new MozillaAddonScope());
    engine.name= platform[0];
    engine.version= platform[1];
    engine.platform= platform[2];
//    self.require('af/addonCore.js'); // <--- does not exist yet. Not sure if it is really needed

//  publish APIs
    self.exports.$= selector;
    self.exports.$_= scopeSelector;

}else if(platform[2] == 'Node'){
    engine.name= platform[0];
    engine.version= platform[1];
    engine.platform= self.process.platform;
    engine.arch= self.process.arch;

//  publish APIs
    self.$= selector;
    self.$_= scopeSelector;
}

})();<|endoftext|>