<commit_before>/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */

"use strict";

const LAST_IID = 'LAST_IID';
const IS_TOUCHED = 0x1;
const CONDITIONAL_TRUE = 0x2;
const CONDITIONAL_FALSE = 0x4;

class Coverage {

    constructor() {
        this._current = {};
    }

	_getFile(file) {
		if (!this._current[file]) {
			this._current[file] = {
				smap: {},
				branches: {},
				lines: {
                  all: new Set(),
                  touched: new Set()
                }
			};
		}
		return this._current[file];
	}

	_addSMap(f, smap) {
		f.smap = smap;
	}

	_mergeBranches(f, branches) {
	    for (let i in branches) {
			f.branches[i] |= branches[i];
		}
	}

    _mergeLineNumbers(touched, all, smap, branches) {

        for (let idx in smap) {
            if (!isNaN(idx)) {
                all.add(smap[idx].line);
            }
        }

        for (let idx in branches) {
            if (!isNaN(idx) && branches[idx]) {
                touched.add(smap[idx].line);
            }
        }

    }

    /**
     * Merges new coverage data from a path with existing data
       */
    add(coverage) {
        for (let i in coverage) {
            if (i != LAST_IID) {
                let file = this._getFile(i);
                this._addSMap(file, coverage[i].smap);
                this._mergeBranches(file, coverage[i].branches);
                this._mergeLineNumbers(file.lines.touched, file.lines.all, coverage[i].smap, coverage[i].branches);
            }
        }
    }

	_termResults(file) {
		let found = 0;
		let total = 0;

		for (let i in file.smap) {
			total++;

            if (file.branches[i] & IS_TOUCHED) {
                found++;
            }
		}

		return {
			found: found,
			total: total,
			coverage: found / total
		}
	}

    _locResults(file) {
        let touchedLines = Array.from(file.lines.touched).sort((a, b) => a - b);
        let allLines = Array.from(file.lines.all).sort((a, b) => a - b);
        return {
            touched: touchedLines,
            all: allLines,
            found: touchedLines.length,
            total: allLines.length,
            coverage: touchedLines.length / allLines.length
        }
    }

    _total(list, field) {
        let found = 0;
        let total = 0;

        for (let file of list) {
            found += file[field].found;
            total += file[field].total;
        }

        return total != 0 ? (found / total) : 0;
    }

    _decisionResults(file) {
        let conditionalIids = 0;
        let trueTaken = 0;
        let falseTaken = 0;

        for (let i in file.smap) {
            if (i % 4 == 0) {
                conditionalIids++;

                if (file.branches[i] & CONDITIONAL_TRUE) {
                    trueTaken++;
                }

                if (file.branches[i] & CONDITIONAL_FALSE) {
                    falseTaken++;
                }
            }
        }

        const totalPossibleDecisions = 2 * conditionalIids;

        return {
            trueTaken: trueTaken,
            falseTaken: falseTaken,
            totalOptions: totalPossibleDecisions,
            coverage: (trueTaken + falseTaken) / totalPossibleDecisions
        }
    }

    final(includeSmap) {
        let results = [];

        for (let fileName in this._current) {
            let file = this._getFile(fileName);
            results.push({
                file: fileName,
                smap: includeSmap ? file.smap : undefined,
                branches: includeSmap ? file.branches : undefined,
                terms: this._termResults(file),
                loc: this._locResults(file),
                decisions: this._decisionResults(file)
            });
        }

        let [loc, terms] = [this._total(results, 'loc'), this._total(results, 'terms')];

        results.loc = loc;
        results.terms = terms;

        return results;
    }

    /**
     * Final without terms or lines
     * TODO: Doesn't really need to exist
     */
    current() {
        let results = this.final();

        results.forEach(item => {
            delete item.loc.touched;
            delete item.loc.all;
        });

        return results;
    }

    lines() {
        return this.final().reduce((prev, next) => {
            prev[next.file] = {
                all: next.loc.all,
                touched: next.loc.touched
            };
            return prev;
        }, {});
    }
}

export default Coverage;
<commit_msg>Commit fix to coverage aggregator<commit_after>/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */

"use strict";

const LAST_IID = 'LAST_IID';
const IS_TOUCHED = 0x1;
const CONDITIONAL_TRUE = 0x2;
const CONDITIONAL_FALSE = 0x4;

class Coverage {

    constructor() {
        this._current = {};
    }

	_getFile(file) {
		if (!this._current[file]) {
			this._current[file] = {
				smap: {},
				branches: {},
				lines: {
                  all: new Set(),
                  touched: new Set()
                }
			};
		}
		return this._current[file];
	}

	_addSMap(f, smap) {
		f.smap = smap;
	}

	_mergeBranches(f, branches) {
	    for (let i in branches) {
			f.branches[i] |= branches[i];
		}
	}

    _mergeLineNumbers(touched, all, smap, branches) {

        for (let idx in smap) {
            if (!isNaN(idx) && smap[idx] && smap[idx].line) {
                all.add(smap[idx].line);
            }
        }

        for (let idx in branches) {
            if (!isNaN(idx) && branches[idx] && smap[idx] && smap[idx].line) {
                touched.add(smap[idx].line);
            }
        }

    }

    /**
     * Merges new coverage data from a path with existing data
       */
    add(coverage) {
        for (let i in coverage) {
            if (i != LAST_IID) {
                let file = this._getFile(i);
                this._addSMap(file, coverage[i].smap);
                this._mergeBranches(file, coverage[i].branches);
                this._mergeLineNumbers(file.lines.touched, file.lines.all, coverage[i].smap, coverage[i].branches);
            }
        }
    }

	_termResults(file) {
		let found = 0;
		let total = 0;

		for (let i in file.smap) {
			total++;

            if (file.branches[i] & IS_TOUCHED) {
                found++;
            }
		}

		return {
			found: found,
			total: total,
			coverage: found / total
		}
	}

    _locResults(file) {
        let touchedLines = Array.from(file.lines.touched).sort((a, b) => a - b);
        let allLines = Array.from(file.lines.all).sort((a, b) => a - b);
        return {
            touched: touchedLines,
            all: allLines,
            found: touchedLines.length,
            total: allLines.length,
            coverage: touchedLines.length / allLines.length
        }
    }

    _total(list, field) {
        let found = 0;
        let total = 0;

        for (let file of list) {
            found += file[field].found;
            total += file[field].total;
        }

        return total != 0 ? (found / total) : 0;
    }

    _decisionResults(file) {
        let conditionalIids = 0;
        let trueTaken = 0;
        let falseTaken = 0;

        for (let i in file.smap) {
            if (i % 4 == 0) {
                conditionalIids++;

                if (file.branches[i] & CONDITIONAL_TRUE) {
                    trueTaken++;
                }

                if (file.branches[i] & CONDITIONAL_FALSE) {
                    falseTaken++;
                }
            }
        }

        const totalPossibleDecisions = 2 * conditionalIids;

        return {
            trueTaken: trueTaken,
            falseTaken: falseTaken,
            totalOptions: totalPossibleDecisions,
            coverage: (trueTaken + falseTaken) / totalPossibleDecisions
        }
    }

    final(includeSmap) {
        let results = [];

        for (let fileName in this._current) {
            let file = this._getFile(fileName);
            results.push({
                file: fileName,
                smap: includeSmap ? file.smap : undefined,
                branches: includeSmap ? file.branches : undefined,
                terms: this._termResults(file),
                loc: this._locResults(file),
                decisions: this._decisionResults(file)
            });
        }

        let [loc, terms] = [this._total(results, 'loc'), this._total(results, 'terms')];

        results.loc = loc;
        results.terms = terms;

        return results;
    }

    /**
     * Final without terms or lines
     * TODO: Doesn't really need to exist
     */
    current() {
        let results = this.final();

        results.forEach(item => {
            delete item.loc.touched;
            delete item.loc.all;
        });

        return results;
    }

    lines() {
        return this.final().reduce((prev, next) => {
            prev[next.file] = {
                all: next.loc.all,
                touched: next.loc.touched
            };
            return prev;
        }, {});
    }
}

export default Coverage;
<|endoftext|>


<commit_before>/* global define */
define(['jquery', 'tmlib/fx/AnimationTransition', 'tmclasses/tmclasses', 'tmlib/ui/SwitchList', 'tmlib/ua/ua'], function(jQuery, __AnimationTransition, __tmclasses, __SwitchList, __ua){
	//-! temporarily here until it makes its way elsewhere
	var __getElmDimensions = function(_elm){
		var _data = {};
		if(_elm){
			_elm.css({position: 'absolute', visibility: 'hidden'});
			_data.width = _elm.outerWidth();
			_data.height = _elm.outerHeight();
			_elm.css('position', '').css('visibility', '');
		}

		return _data;
	};
	var __this = __tmclasses.create({
		parent: __SwitchList
		,init: function(){
			var _this = this;
			_this.__parent(arguments);
			if(_this.$){
				if(_this.actionSelector){
					//--prevent click handling on interactive sub-elements
					if(_this.interactiveTagNames && _this.interactiveTagNames.length){
						var _actions = _this.actionSelector.split(',');
						var _subActions = [];
						for(var _i = 0; _i < _actions.length; ++_i){
							for(var _j = 0; _j < _this.interactiveTagNames.length; ++_j){
								_subActions.push(_actions[_i] + ' ' + _this.interactiveTagNames[_j]);
							}
						}
					}
					_this.$.on('click', _subActions.join(',') , function(_event){
						_event.stopPropagation();
					});

					//--attach click handler
					_this.$.on('click', _this.actionSelector, function(_event){
						_event.preventDefault();
						var $this = jQuery(this);
						_this.switchToItem($this.closest('.expandGalleryItem'));
					});
				}
				if(_this.doLazyLoadIFrames){
					//--disable 'src' of iframes so they won't be loaded until needed
					_this.$.find('.expandGalleryItemDetail').find('iframe').each(function(){
						var _$ = jQuery(this);
						if(_$.attr('src')){
							_$.data('src', _$.attr('src'));
							_$.attr('src', '');
						}
					});
				}
			}
			var _postLoad = function(){
				var _initial = _this.items.find(_this.actionSelector).filter('.' + _this.currentClass).removeClass(_this.currentClass).first();
				if(_initial.length){
					_this.switchToItem(_initial, {duration: 0, scrollToItem: false});
				}
				_this.$.attr('data-inited', 'true');
				_this.inited = true;
			};
			if(_this.doEqualizeRowHeights){
				if(_this.responsiveHandler){
					_this.responsiveHandler.sub('resize', jQuery.proxy(_this.equalizeRowsHeights, _this));
				}
				//--equalize heights initially.  make sure images are loaded so heights are correct
				_this.equalizeRowsHeights();
				var _images = _this.$.find(_this.getItemSelector()).find('img');
				if(_images.length){
					_images.on('load', function(){
						_this.equalizeRowsHeights();
						_postLoad();
					});
					setTimeout(function(){
						if(!_this.inited){
							_postLoad();
						}
					}, 1000);
				}else{
					_postLoad();
				}
			}else{
				_postLoad();
			}
		}
		,properties: {
			$: null
			,actionSelector: '.expandGalleryItemAction'
			,autoStart: false
			,duration: 200
			,doEqualizeRowHeights: false
			,doLazyLoadIFrames: true
			/*
			Property: equalizeOffsetDeviation
			Pixel deviation of top of item used in the `equalizeRowsHeights()` method for determining if items are in same row.  Ran into an instance where it was off by one pixel for no visible reason.
			*/
			,equalizeOffsetDeviation: 1
			,equalizeRowHeights: function(_rowItems){
				var _i;
				var _item;
				var _height;
				var _maxHeight = 0;
				var _length = _rowItems.length;
				if(_length > 1){
					for(_i = 0; _i < _length; ++_i){
						_item = _rowItems[_i];
						_height = _item.outerHeight();
						if(_height > _maxHeight){
							_maxHeight = _height;
						}
					}
					for(_i = 0; _i < _length; ++_i){
						_item = _rowItems[_i];
						_item.css('height', _maxHeight);
					}
				}
			}
			/*
			Method: equalizeRowsHeights
			Equalize height of items in each row so that expanded content doesn't get overlapped by taller items in same row.
			*/
			,equalizeRowsHeights: function(){
				if(!(__ua.isIE() && __ua.getVersion() < 8)){ //-# ie7 seems to get into infinite loop with this
					var _this = this;
					var _bp = _this.responsiveHandler.getBreakPoint();
					if(_this.$){
						var $actions = _this.$.find(_this.getItemSelector());
						if(_this.isNVP(_bp)){
							$actions.css('height', '');
						}else{
							var _previousPosition;
							var _previousRowItems = [];
							$actions.css('height', '');
							$actions.each(function(){
								var $this = jQuery(this);
								var _position = $this.offset().top;

								if((_position >= _previousPosition - _this.equalizeOffsetDeviation && _position <= _previousPosition + _this.equalizeOffsetDeviation) || _previousPosition === undefined){
									_previousRowItems.push($this);
								}else{
									_this.equalizeRowHeights(_previousRowItems);
									_previousRowItems = [];
									_previousRowItems.push($this);
								}
								_previousPosition = _position;
							});
							_this.equalizeRowHeights(_previousRowItems);
						}
					}
				}
			}
			,expandContainerSelector: 'this'
			,getExpandContainer: function(_item){
				if(this.getExpandContainerSelector() === 'this' || !_item){
					return _item;
				}else{
					return _item.closest(this.getExpandContainerSelector());
				}
			}
			,getExpandContainerSelector: function(){
				return this.expandContainerSelector;
			}
			,getItemDetail: function(_item){
				if(_item){
					if(!_item.data('expandGalleryDetail')){
						_item.data('expandGalleryDetail', _item.find('.expandGalleryItemDetail'));
					}
					return _item.data('expandGalleryDetail');
				}else{
					return null;
				}
			}
			,getItemSelector: function(){
				return this.itemSelector;
			}
			//,getTransElements: function(_item, _opts){
			//	var _current = (this.current) ? this.getExpandContainer(this.current) : null;
			//	var _next = (_item) ? this.getExpandContainer(_item) : null;
			//	return [
			//		_current
			//		,_item
			//		,this.currentNav
			//		,_opts.newNav
			//	];
			//}
			/*
			Property: interactiveTagNames
			Tags that won't trigger click on action.  Meant to allow child interactive elements to be usable.
			*/
			,interactiveTagNames: ['a','button','input','label','select','textarea']
			,isNVP: function(_bp){
				return this.responsiveHandler && this.responsiveHandler.isNVP(_bp) || false;
			}
			,itemSelector: '.expandGalleryItem'
			,inited: false
			,responsiveHandler: undefined
			/*
			Property: scrollContainer
			Get copy of body/html element for use by scrollToItem action of open transition.  Seem to need both to be cross browser safe
			*/
			,scrollContainer: undefined
			,getScrollContainer: function(){
				if(!this.scrollContainer){
					this.scrollContainer = jQuery('body,html');
				}
				return this.scrollContainer;
			}
			/*
			Method: getScrollElement
			Given transition data, returns the element 'scrollToItem' scrolls to.
			*/
			,getScrollElement: function(_data){
				return _data.elements[3] || null;
			}
			/*
			Method: onOpen
			Called after opening transition, if defined.
			*/
			,onOpen: function(_data){
				var _this = this;
				if(_this.doLazyLoadIFrames){
					_data.elements[3].find('iframe').each(function(){
						var _$ = jQuery(this);
						if(!_$.attr('src')){
							_$.attr('src', _$.data('src'));
						}
					});
				}
				if(typeof _data.scrollToItem !== 'undefined' ? _data.scrollToItem : _this.scrollToItem){
					_this.scrollToItem(_data);
				}
			}
			/*
			Method: scrollToItem
			Called after transition, will scroll to the opened item so that it isn't out of view
			Arguments:
				_data(Array): _data from transition
			*/
			,scrollToItem: function(_data){
				var _elm = this.getScrollElement(_data);
				if(_elm){
					var _scrollTo = _elm.offset().top - this.scrollToOffset;
					if(_scrollTo < 0){
						_scrollTo = 0;
					}
					this.getScrollContainer().animate({
						scrollTop: _scrollTo
					}, this.duration);
				}
			}
			,scrollToOffset: 100
			,transition: function(_opts){
				if(_opts && _opts.elements && _opts.elements.length){
					var _this = this;
					var _old = _opts.elements[0];
					var _new = _opts.elements[1];
					var _oldTarget = (_this.getExpandContainerSelector() === 'this') ? _old : _this.getExpandContainer(_old);
					var _newTarget = (_this.getExpandContainerSelector() === 'this') ? _new : _this.getExpandContainer(_new);
					_opts.elements = [
						(_newTarget.is(_oldTarget)) ? null : _oldTarget
						,_this.getItemDetail(_old)
						,_newTarget
						,_this.getItemDetail(_new)
					];
					if(_old && _old.is(_new)){
						_opts.after = function(){
							_new.removeClass('current');
							_this.current = undefined;
							if(_this.nav){
								_this.currentNav = undefined;
							}
							_this.isTransitioning = false;
						};
						_this.transitionClose.transitionForElements(_opts);
					}else{
						_this.transitionOpen.transitionForElements(_opts);
					}
				}
			}
			,getTransition: function(){
				var _this = this;
				/*-# elements
				1: previous item
				2: previous item detail
				3: next item
				4: next item detail
				*/
				if(!_this.transitionOpen){
					_this.transitionOpen = __this.getDefaultTransitionOpen(null, _this);
				}
				if(!_this.transitionClose){
					_this.transitionClose = __this.getDefaultTransitionClose(null, _this);
				}
				return _this.transition;
			}
			,transitionClose: undefined
			,transitionOpen: undefined
		}
		,statics: {
			getDefaultTransitionOpen: function(_opts, _this){
				var _defaults = {
					duration: (_this) ? _this.duration : 200
					,stylesBefore: [
						null
						,null
						,function(_elm){
							_elm.data('paddingBottom', _elm.css('padding-bottom'));
						}
						,function(_elm){
							var _styles = {display: 'block', height: 0};
							if(_elm){
								// var _container = _opts.elements[2];
								var _height = __getElmDimensions(_elm).height;
								//_styles.top = _container.position().top + _container.outerHeight();
								_elm.data('height', _height);

								//--capture margin so we can easily add extra space around detail container
								//-# must make sure margins are numeric
								var _marginBottom = parseInt(_elm.css('margin-bottom').replace('px', ''),10);
								var _marginTop = parseInt(_elm.css('margin-top').replace('px', ''),10);
								var _margin = (!isNaN(_marginBottom) ? _marginBottom : 0) + (!isNaN(_marginTop) ? _marginTop : 0);
								_elm.data('margin', _margin);
							}
							return _styles;
						}
					]
					,stylesTransition: [
						function(_elm){
							if(_elm){
								return {
									paddingBottom: _elm.data('paddingBottom')
								};
							}
						}
						,{height: 0}
						,function(_elm, _opts){
							return {
								paddingBottom: _opts.elements[3].data('height') + _opts.elements[3].data('margin')
							};
						}
						,function(_elm){
							return {
								height: _elm.data('height')
							};
						}
					]
					,stylesAfter: [
						{paddingBottom: ''}
						,{display: '', height: ''}
					]
					,onAfter: function(_data){
						if(_this){
							if(_this.onOpen){
								_this.onOpen(_data);
							}
							_this.pub('open', _data);
						}
						__AnimationTransition.prototype.onAfter.apply(this, arguments);
					}
				};
				if(_opts){
					jQuery.extend(_defaults, _opts);
				}
				return new __AnimationTransition(_defaults);
			}
			,getDefaultTransitionClose: function(_opts, _this){
				var _defaults = {
					duration: (_this) ? _this.duration : 200
					,stylesBefore: [
						null
						,null
						,null
						,null
					]
					,stylesTransition: [
						null
						,null
						,function(_elm){
							if(_elm){
								return {
									paddingBottom: _elm.data('paddingBottom')
								};
							}
						}
						,{height: 0}
					]
					,stylesAfter: [
						null
						,null
						,{paddingBottom: ''}
						,{display: '', height: ''}
					]
					,onAfter: function(_data){
						if(_this){
							_this.pub('close', _data);
						}
						__AnimationTransition.prototype.onAfter.apply(this, arguments);
					}
				};
				if(_opts){
					jQuery.extend(_defaults, _opts);
				}
				return new __AnimationTransition(_defaults);
			}
		}
	});
	return __this;
});
<commit_msg>expandgallery: wasn't finding initial item if current class set on item instead of action. now looks at both<commit_after>/* global define */
define(['jquery', 'tmlib/fx/AnimationTransition', 'tmclasses/tmclasses', 'tmlib/ui/SwitchList', 'tmlib/ua/ua'], function(jQuery, __AnimationTransition, __tmclasses, __SwitchList, __ua){
	//-! temporarily here until it makes its way elsewhere
	var __getElmDimensions = function(_elm){
		var _data = {};
		if(_elm){
			_elm.css({position: 'absolute', visibility: 'hidden'});
			_data.width = _elm.outerWidth();
			_data.height = _elm.outerHeight();
			_elm.css('position', '').css('visibility', '');
		}

		return _data;
	};
	var __this = __tmclasses.create({
		parent: __SwitchList
		,init: function(){
			var _this = this;
			_this.__parent(arguments);
			if(_this.$){
				if(_this.actionSelector){
					//--prevent click handling on interactive sub-elements
					if(_this.interactiveTagNames && _this.interactiveTagNames.length){
						var _actions = _this.actionSelector.split(',');
						var _subActions = [];
						for(var _i = 0; _i < _actions.length; ++_i){
							for(var _j = 0; _j < _this.interactiveTagNames.length; ++_j){
								_subActions.push(_actions[_i] + ' ' + _this.interactiveTagNames[_j]);
							}
						}
					}
					_this.$.on('click', _subActions.join(',') , function(_event){
						_event.stopPropagation();
					});

					//--attach click handler
					_this.$.on('click', _this.actionSelector, function(_event){
						_event.preventDefault();
						var $this = jQuery(this);
						_this.switchToItem($this.closest('.expandGalleryItem'));
					});
				}
				if(_this.doLazyLoadIFrames){
					//--disable 'src' of iframes so they won't be loaded until needed
					_this.$.find('.expandGalleryItemDetail').find('iframe').each(function(){
						var _$ = jQuery(this);
						if(_$.attr('src')){
							_$.data('src', _$.attr('src'));
							_$.attr('src', '');
						}
					});
				}
			}
			var _postLoad = function(){
				var _initial = _this.items.find(_this.actionSelector + ',' + _this.getItemSelector()).filter('.' + _this.currentClass).removeClass(_this.currentClass).first();
				if(_initial.length){
					_this.switchToItem(_initial, {duration: 0, scrollToItem: false});
				}
				_this.$.attr('data-inited', 'true');
				_this.inited = true;
			};
			if(_this.doEqualizeRowHeights){
				if(_this.responsiveHandler){
					_this.responsiveHandler.sub('resize', jQuery.proxy(_this.equalizeRowsHeights, _this));
				}
				//--equalize heights initially.  make sure images are loaded so heights are correct
				_this.equalizeRowsHeights();
				var _images = _this.$.find(_this.getItemSelector()).find('img');
				if(_images.length){
					_images.on('load', function(){
						_this.equalizeRowsHeights();
						_postLoad();
					});
					setTimeout(function(){
						if(!_this.inited){
							_postLoad();
						}
					}, 1000);
				}else{
					_postLoad();
				}
			}else{
				_postLoad();
			}
		}
		,properties: {
			$: null
			,actionSelector: '.expandGalleryItemAction'
			,autoStart: false
			,duration: 200
			,doEqualizeRowHeights: false
			,doLazyLoadIFrames: true
			/*
			Property: equalizeOffsetDeviation
			Pixel deviation of top of item used in the `equalizeRowsHeights()` method for determining if items are in same row.  Ran into an instance where it was off by one pixel for no visible reason.
			*/
			,equalizeOffsetDeviation: 1
			,equalizeRowHeights: function(_rowItems){
				var _i;
				var _item;
				var _height;
				var _maxHeight = 0;
				var _length = _rowItems.length;
				if(_length > 1){
					for(_i = 0; _i < _length; ++_i){
						_item = _rowItems[_i];
						_height = _item.outerHeight();
						if(_height > _maxHeight){
							_maxHeight = _height;
						}
					}
					for(_i = 0; _i < _length; ++_i){
						_item = _rowItems[_i];
						_item.css('height', _maxHeight);
					}
				}
			}
			/*
			Method: equalizeRowsHeights
			Equalize height of items in each row so that expanded content doesn't get overlapped by taller items in same row.
			*/
			,equalizeRowsHeights: function(){
				if(!(__ua.isIE() && __ua.getVersion() < 8)){ //-# ie7 seems to get into infinite loop with this
					var _this = this;
					var _bp = _this.responsiveHandler.getBreakPoint();
					if(_this.$){
						var $actions = _this.$.find(_this.getItemSelector());
						if(_this.isNVP(_bp)){
							$actions.css('height', '');
						}else{
							var _previousPosition;
							var _previousRowItems = [];
							$actions.css('height', '');
							$actions.each(function(){
								var $this = jQuery(this);
								var _position = $this.offset().top;

								if((_position >= _previousPosition - _this.equalizeOffsetDeviation && _position <= _previousPosition + _this.equalizeOffsetDeviation) || _previousPosition === undefined){
									_previousRowItems.push($this);
								}else{
									_this.equalizeRowHeights(_previousRowItems);
									_previousRowItems = [];
									_previousRowItems.push($this);
								}
								_previousPosition = _position;
							});
							_this.equalizeRowHeights(_previousRowItems);
						}
					}
				}
			}
			,expandContainerSelector: 'this'
			,getExpandContainer: function(_item){
				if(this.getExpandContainerSelector() === 'this' || !_item){
					return _item;
				}else{
					return _item.closest(this.getExpandContainerSelector());
				}
			}
			,getExpandContainerSelector: function(){
				return this.expandContainerSelector;
			}
			,getItemDetail: function(_item){
				if(_item){
					if(!_item.data('expandGalleryDetail')){
						_item.data('expandGalleryDetail', _item.find('.expandGalleryItemDetail'));
					}
					return _item.data('expandGalleryDetail');
				}else{
					return null;
				}
			}
			,getItemSelector: function(){
				return this.itemSelector;
			}
			//,getTransElements: function(_item, _opts){
			//	var _current = (this.current) ? this.getExpandContainer(this.current) : null;
			//	var _next = (_item) ? this.getExpandContainer(_item) : null;
			//	return [
			//		_current
			//		,_item
			//		,this.currentNav
			//		,_opts.newNav
			//	];
			//}
			/*
			Property: interactiveTagNames
			Tags that won't trigger click on action.  Meant to allow child interactive elements to be usable.
			*/
			,interactiveTagNames: ['a','button','input','label','select','textarea']
			,isNVP: function(_bp){
				return this.responsiveHandler && this.responsiveHandler.isNVP(_bp) || false;
			}
			,itemSelector: '.expandGalleryItem'
			,inited: false
			,responsiveHandler: undefined
			/*
			Property: scrollContainer
			Get copy of body/html element for use by scrollToItem action of open transition.  Seem to need both to be cross browser safe
			*/
			,scrollContainer: undefined
			,getScrollContainer: function(){
				if(!this.scrollContainer){
					this.scrollContainer = jQuery('body,html');
				}
				return this.scrollContainer;
			}
			/*
			Method: getScrollElement
			Given transition data, returns the element 'scrollToItem' scrolls to.
			*/
			,getScrollElement: function(_data){
				return _data.elements[3] || null;
			}
			/*
			Method: onOpen
			Called after opening transition, if defined.
			*/
			,onOpen: function(_data){
				var _this = this;
				if(_this.doLazyLoadIFrames){
					_data.elements[3].find('iframe').each(function(){
						var _$ = jQuery(this);
						if(!_$.attr('src')){
							_$.attr('src', _$.data('src'));
						}
					});
				}
				if(typeof _data.scrollToItem !== 'undefined' ? _data.scrollToItem : _this.scrollToItem){
					_this.scrollToItem(_data);
				}
			}
			/*
			Method: scrollToItem
			Called after transition, will scroll to the opened item so that it isn't out of view
			Arguments:
				_data(Array): _data from transition
			*/
			,scrollToItem: function(_data){
				var _elm = this.getScrollElement(_data);
				if(_elm){
					var _scrollTo = _elm.offset().top - this.scrollToOffset;
					if(_scrollTo < 0){
						_scrollTo = 0;
					}
					this.getScrollContainer().animate({
						scrollTop: _scrollTo
					}, this.duration);
				}
			}
			,scrollToOffset: 100
			,transition: function(_opts){
				if(_opts && _opts.elements && _opts.elements.length){
					var _this = this;
					var _old = _opts.elements[0];
					var _new = _opts.elements[1];
					var _oldTarget = (_this.getExpandContainerSelector() === 'this') ? _old : _this.getExpandContainer(_old);
					var _newTarget = (_this.getExpandContainerSelector() === 'this') ? _new : _this.getExpandContainer(_new);
					_opts.elements = [
						(_newTarget.is(_oldTarget)) ? null : _oldTarget
						,_this.getItemDetail(_old)
						,_newTarget
						,_this.getItemDetail(_new)
					];
					if(_old && _old.is(_new)){
						_opts.after = function(){
							_new.removeClass('current');
							_this.current = undefined;
							if(_this.nav){
								_this.currentNav = undefined;
							}
							_this.isTransitioning = false;
						};
						_this.transitionClose.transitionForElements(_opts);
					}else{
						_this.transitionOpen.transitionForElements(_opts);
					}
				}
			}
			,getTransition: function(){
				var _this = this;
				/*-# elements
				1: previous item
				2: previous item detail
				3: next item
				4: next item detail
				*/
				if(!_this.transitionOpen){
					_this.transitionOpen = __this.getDefaultTransitionOpen(null, _this);
				}
				if(!_this.transitionClose){
					_this.transitionClose = __this.getDefaultTransitionClose(null, _this);
				}
				return _this.transition;
			}
			,transitionClose: undefined
			,transitionOpen: undefined
		}
		,statics: {
			getDefaultTransitionOpen: function(_opts, _this){
				var _defaults = {
					duration: (_this) ? _this.duration : 200
					,stylesBefore: [
						null
						,null
						,function(_elm){
							_elm.data('paddingBottom', _elm.css('padding-bottom'));
						}
						,function(_elm){
							var _styles = {display: 'block', height: 0};
							if(_elm){
								// var _container = _opts.elements[2];
								var _height = __getElmDimensions(_elm).height;
								//_styles.top = _container.position().top + _container.outerHeight();
								_elm.data('height', _height);

								//--capture margin so we can easily add extra space around detail container
								//-# must make sure margins are numeric
								var _marginBottom = parseInt(_elm.css('margin-bottom').replace('px', ''),10);
								var _marginTop = parseInt(_elm.css('margin-top').replace('px', ''),10);
								var _margin = (!isNaN(_marginBottom) ? _marginBottom : 0) + (!isNaN(_marginTop) ? _marginTop : 0);
								_elm.data('margin', _margin);
							}
							return _styles;
						}
					]
					,stylesTransition: [
						function(_elm){
							if(_elm){
								return {
									paddingBottom: _elm.data('paddingBottom')
								};
							}
						}
						,{height: 0}
						,function(_elm, _opts){
							return {
								paddingBottom: _opts.elements[3].data('height') + _opts.elements[3].data('margin')
							};
						}
						,function(_elm){
							return {
								height: _elm.data('height')
							};
						}
					]
					,stylesAfter: [
						{paddingBottom: ''}
						,{display: '', height: ''}
					]
					,onAfter: function(_data){
						if(_this){
							if(_this.onOpen){
								_this.onOpen(_data);
							}
							_this.pub('open', _data);
						}
						__AnimationTransition.prototype.onAfter.apply(this, arguments);
					}
				};
				if(_opts){
					jQuery.extend(_defaults, _opts);
				}
				return new __AnimationTransition(_defaults);
			}
			,getDefaultTransitionClose: function(_opts, _this){
				var _defaults = {
					duration: (_this) ? _this.duration : 200
					,stylesBefore: [
						null
						,null
						,null
						,null
					]
					,stylesTransition: [
						null
						,null
						,function(_elm){
							if(_elm){
								return {
									paddingBottom: _elm.data('paddingBottom')
								};
							}
						}
						,{height: 0}
					]
					,stylesAfter: [
						null
						,null
						,{paddingBottom: ''}
						,{display: '', height: ''}
					]
					,onAfter: function(_data){
						if(_this){
							_this.pub('close', _data);
						}
						__AnimationTransition.prototype.onAfter.apply(this, arguments);
					}
				};
				if(_opts){
					jQuery.extend(_defaults, _opts);
				}
				return new __AnimationTransition(_defaults);
			}
		}
	});
	return __this;
});
<|endoftext|>


<commit_before>var functionMetadataStorage = new Map(),
    emptyArray = Object.freeze([]),
    locateFunctionMetadataElsewhere;

/**
* Stores metadata and provides helpers for searching and adding to it.
*
* @class MetadataStorage
*/
class MetadataStorage {
  constructor(metadata, owner){
    this.metadata = metadata;
    this.owner = owner;
  }

  /**
  * Searches metadata and returns the first instance of a particular type.
  *
  * @method first
  * @param {Function} type The metadata type to look for.
  * @param {Boolean} searchPrototype Indicates whether or not to search the inheritance hierarchy for metadata.
  * @return {Object} Returns an instance of the specified metadata type if found; otherwise null.
  */
  first(type, searchPrototype){
    var metadata = this.metadata,
        i, ii, potential;

    if(metadata === undefined || metadata.length === 0){
      if(searchPrototype && this.owner !== undefined){
        return Metadata.on(Object.getPrototypeOf(this.owner)).first(type, searchPrototype);
      }

      return null;
    }

    for(i = 0, ii = metadata.length; i < ii; ++i){
      potential = metadata[i];

      if(potential instanceof type){
        return potential;
      }
    }

    if(searchPrototype && this.owner !== undefined){
      return Metadata.on(Object.getPrototypeOf(this.owner)).first(type, searchPrototype);
    }

    return null;
  }

  /**
  * Searches metadata for all instances of a particular type.
  *
  * @method all
  * @param {Function} type The metadata type to look for.
  * @param {Boolean} searchPrototype Indicates whether or not to search the inheritance hierarchy for metadata.
  * @return {Array} Returns an array of the specified metadata type.
  */
  all(type, searchPrototype){
    var metadata = this.metadata,
        i, ii, found, potential;

    if(metadata === undefined || metadata.length === 0){
      if(searchPrototype && this.owner !== undefined){
        return Metadata.on(Object.getPrototypeOf(this.owner)).all(type, searchPrototype);
      }

      return emptyArray;
    }

    found = [];

    for(i = 0, ii = metadata.length; i < ii; ++i){
      potential = metadata[i];

      if(potential instanceof type){
        found.push(potential);
      }
    }

    if(searchPrototype && this.owner !== undefined){
      found = found.concat(Metadata.on(Object.getPrototypeOf(this.owner)).all(type, searchPrototype));
    }

    return found;
  }

  /**
  * Adds metadata.
  *
  * @method add
  * @param {Object} instance The metadata instance to add.
  */
  add(instance){
    if(this.metadata === undefined){
      this.metadata = [];
    }

    this.metadata.push(instance);
    return this;
  }
}

MetadataStorage.empty = Object.freeze(new MetadataStorage());

function normalize(metadata, fn, replace){
  if(metadata instanceof MetadataStorage){
    if(replace){
      fn.metadata = function() { return metadata; };
    }

    metadata.owner = fn;
    return metadata;
  }

  if(Array.isArray(metadata)){
    return new MetadataStorage(metadata, fn);
  }

  throw new Error(`Incorrect metadata format for ${metadata}.`);
}

/**
* Provides access to metadata.
*
* @class Metadata
* @static
*/
export var Metadata = {
  /**
  * Locates the metadata on the owner.
  *
  * @method on
  * @param {Function} owner The owner of the metadata.
  * @return {MetadataStorage} Returns the stored metadata.
  */
  on(owner){
    var metadata;

    if(!owner){
      return MetadataStorage.empty;
    }

    metadata = functionMetadataStorage.get(owner);

    if(metadata === undefined){
      if('metadata' in owner){
        if(typeof owner.metadata === 'function'){
          functionMetadataStorage.set(owner, metadata = normalize(owner.metadata(), owner, true));
        }else{
          functionMetadataStorage.set(owner, metadata = normalize(owner.metadata, owner));
        }
      }else if(locateFunctionMetadataElsewhere !== undefined){
        metadata = locateFunctionMetadataElsewhere(owner);

        if(metadata === undefined){
          functionMetadataStorage.set(owner, metadata = new MetadataStorage(undefined, owner));
        }else{
          functionMetadataStorage.set(owner, metadata = normalize(metadata, owner));
        }
      }else{
        functionMetadataStorage.set(owner, metadata = new MetadataStorage(undefined, owner));
      }
    }

    return metadata;
  },
  configure:{
    /**
    * Adds an additional location to search for metadata in.
    *
    * @method location
    * @param {String} staticPropertyName The name of the property on the function instance to search for metadata.
    */
    location(staticPropertyName){
      this.locator(function(fn){return fn[staticPropertyName];});
    },
    /**
    * Adds a function capable of locating metadata.
    *
    * @method locator
    * @param {Function} locator Configures a function which searches for metadata. It should return undefined if none is found.
    */
    locator(locator){
      if(locateFunctionMetadataElsewhere === undefined){
        locateFunctionMetadataElsewhere = locator;
        return;
      }

      var original = locateFunctionMetadataElsewhere;
      locateFunctionMetadataElsewhere = function(fn){return original(fn) || locator(fn);};
    },
    classHelper(name, fn){
      MetadataStorage.prototype[name] = function(){
        var context = Object.create(fn.prototype);
        var metadata = fn.apply(context, arguments) || context;
        this.add(metadata);
        return this;
      };

      Metadata[name] = function(){
        var storage = new MetadataStorage([]);
        return storage[name].apply(storage, arguments);
      };
    },
    functionHelper(name, fn){
      MetadataStorage.prototype[name] = function(){
        fn.apply(this, arguments);
        return this;
      };

      Metadata[name] = function(){
        var storage = new MetadataStorage([]);
        return storage[name].apply(storage, arguments);
      };
    }
  }
}<commit_msg>feat(metadata): add a "has" helper to MetadataStorage<commit_after>var functionMetadataStorage = new Map(),
    emptyArray = Object.freeze([]),
    locateFunctionMetadataElsewhere;

/**
* Stores metadata and provides helpers for searching and adding to it.
*
* @class MetadataStorage
*/
class MetadataStorage {
  constructor(metadata, owner){
    this.metadata = metadata;
    this.owner = owner;
  }

  /**
  * Searches metadata and returns the first instance of a particular type.
  *
  * @method first
  * @param {Function} type The metadata type to look for.
  * @param {Boolean} searchPrototype Indicates whether or not to search the inheritance hierarchy for metadata.
  * @return {Object} Returns an instance of the specified metadata type if found; otherwise null.
  */
  first(type, searchPrototype){
    var metadata = this.metadata,
        i, ii, potential;

    if(metadata === undefined || metadata.length === 0){
      if(searchPrototype && this.owner !== undefined){
        return Metadata.on(Object.getPrototypeOf(this.owner)).first(type, searchPrototype);
      }

      return null;
    }

    for(i = 0, ii = metadata.length; i < ii; ++i){
      potential = metadata[i];

      if(potential instanceof type){
        return potential;
      }
    }

    if(searchPrototype && this.owner !== undefined){
      return Metadata.on(Object.getPrototypeOf(this.owner)).first(type, searchPrototype);
    }

    return null;
  }

  has(type, searchPrototype){
    return this.first(type, searchPrototype) !== null;
  }

  /**
  * Searches metadata for all instances of a particular type.
  *
  * @method all
  * @param {Function} type The metadata type to look for.
  * @param {Boolean} searchPrototype Indicates whether or not to search the inheritance hierarchy for metadata.
  * @return {Array} Returns an array of the specified metadata type.
  */
  all(type, searchPrototype){
    var metadata = this.metadata,
        i, ii, found, potential;

    if(metadata === undefined || metadata.length === 0){
      if(searchPrototype && this.owner !== undefined){
        return Metadata.on(Object.getPrototypeOf(this.owner)).all(type, searchPrototype);
      }

      return emptyArray;
    }

    found = [];

    for(i = 0, ii = metadata.length; i < ii; ++i){
      potential = metadata[i];

      if(potential instanceof type){
        found.push(potential);
      }
    }

    if(searchPrototype && this.owner !== undefined){
      found = found.concat(Metadata.on(Object.getPrototypeOf(this.owner)).all(type, searchPrototype));
    }

    return found;
  }

  /**
  * Adds metadata.
  *
  * @method add
  * @param {Object} instance The metadata instance to add.
  */
  add(instance){
    if(this.metadata === undefined){
      this.metadata = [];
    }

    this.metadata.push(instance);
    return this;
  }
}

MetadataStorage.empty = Object.freeze(new MetadataStorage());

function normalize(metadata, fn, replace){
  if(metadata instanceof MetadataStorage){
    if(replace){
      fn.metadata = function() { return metadata; };
    }

    metadata.owner = fn;
    return metadata;
  }

  if(Array.isArray(metadata)){
    return new MetadataStorage(metadata, fn);
  }

  throw new Error(`Incorrect metadata format for ${metadata}.`);
}

/**
* Provides access to metadata.
*
* @class Metadata
* @static
*/
export var Metadata = {
  /**
  * Locates the metadata on the owner.
  *
  * @method on
  * @param {Function} owner The owner of the metadata.
  * @return {MetadataStorage} Returns the stored metadata.
  */
  on(owner){
    var metadata;

    if(!owner){
      return MetadataStorage.empty;
    }

    metadata = functionMetadataStorage.get(owner);

    if(metadata === undefined){
      if('metadata' in owner){
        if(typeof owner.metadata === 'function'){
          functionMetadataStorage.set(owner, metadata = normalize(owner.metadata(), owner, true));
        }else{
          functionMetadataStorage.set(owner, metadata = normalize(owner.metadata, owner));
        }
      }else if(locateFunctionMetadataElsewhere !== undefined){
        metadata = locateFunctionMetadataElsewhere(owner);

        if(metadata === undefined){
          functionMetadataStorage.set(owner, metadata = new MetadataStorage(undefined, owner));
        }else{
          functionMetadataStorage.set(owner, metadata = normalize(metadata, owner));
        }
      }else{
        functionMetadataStorage.set(owner, metadata = new MetadataStorage(undefined, owner));
      }
    }

    return metadata;
  },
  configure:{
    /**
    * Adds an additional location to search for metadata in.
    *
    * @method location
    * @param {String} staticPropertyName The name of the property on the function instance to search for metadata.
    */
    location(staticPropertyName){
      this.locator(function(fn){return fn[staticPropertyName];});
    },
    /**
    * Adds a function capable of locating metadata.
    *
    * @method locator
    * @param {Function} locator Configures a function which searches for metadata. It should return undefined if none is found.
    */
    locator(locator){
      if(locateFunctionMetadataElsewhere === undefined){
        locateFunctionMetadataElsewhere = locator;
        return;
      }

      var original = locateFunctionMetadataElsewhere;
      locateFunctionMetadataElsewhere = function(fn){return original(fn) || locator(fn);};
    },
    classHelper(name, fn){
      MetadataStorage.prototype[name] = function(){
        var context = Object.create(fn.prototype);
        var metadata = fn.apply(context, arguments) || context;
        this.add(metadata);
        return this;
      };

      Metadata[name] = function(){
        var storage = new MetadataStorage([]);
        return storage[name].apply(storage, arguments);
      };
    },
    functionHelper(name, fn){
      MetadataStorage.prototype[name] = function(){
        fn.apply(this, arguments);
        return this;
      };

      Metadata[name] = function(){
        var storage = new MetadataStorage([]);
        return storage[name].apply(storage, arguments);
      };
    }
  }
}<|endoftext|>


<commit_before>import React from 'react';
import Link from 'gatsby-link';
import Browser from '../components/Browser';

const IndexPage = () => (

          <Link class="btn btn-outline-secondary mr-2" to="/components">
            Documentation
          </Link>

            Github

            Changelog

            v1

            v2

        <Browser />

            The Availity UIKit is derived from Bootstrap 4 and allows developers
            to create stunning web applications for the Availity Spaces platform.{' '}

            This guide will document any modifications done to the Bootstrap framework. Original Bootstrap conventions
            were preserved as much as possible.

            The Availity UIKit is available through Github,{' '}
            NPM.{' '}

);

export default IndexPage;
<commit_msg>docs: fix version links<commit_after>import React from 'react';
import Link from 'gatsby-link';
import Browser from '../components/Browser';

const IndexPage = () => (

          <Link class="btn btn-outline-secondary mr-2" to="/components">
            Documentation
          </Link>

            Github

            Changelog

            v1

            v2

        <Browser />

            The Availity UIKit is derived from Bootstrap 4 and allows developers
            to create stunning web applications for the Availity Spaces platform.{' '}

            This guide will document any modifications done to the Bootstrap framework. Original Bootstrap conventions
            were preserved as much as possible.

            The Availity UIKit is available through Github,{' '}
            NPM.{' '}

);

export default IndexPage;
<|endoftext|>


<commit_before>'use strict'
var fs = require('fs');
var _  = require('lodash');

//bullPen format is =[{c1},{c2},{c3}]
var bullPen            = []
var theCompetitionMat  = []
var winnersBracket     = []
var losersBracket      = []
var competitorsSquared = 2

//k is the maximal number of points a player can win/lose in a given match
var k = 10
var n = 1

var firstCompetitor       = null
var firstCompetitorName   = null
var firstCompetitorRating = null
var firstCompetitorWins   = 0
var firstCompetitorLosses = 0
var firstCompetitorsProbabilityOfVictory  = 0
var firstCompetitorRecord = null

var secondCompetitor       = null
var secondCompetitorName   = null
var secondCompetitorRating = null
var secondCompetitorWins   = 0
var secondCompetitorLosses = 0
var secondCompetitorsProbabilityOfVictory = 0
var secondCompetitorRecord = null

var bullPenGenerator = function(integer) {
  var squaredNumber = integer * integer
  var competitorAssembler = function (squaredNumber) {
    console.log("Number of Competitors In Your Tournament:",squaredNumber)
    for (var j = 1; j <= squaredNumber; j++) {
      let yourNumber = j.toString()
      let competitorBlueprint = '{"c' + yourNumber
                                      + '":{"rating":1600,"wins":0,"losses":0,"record":"","opponents":""}}'

      bullPen.push(JSON.parse(competitorBlueprint))
    }
  }
  competitorAssembler(squaredNumber)
}

/**
 * @name - competitionMatPopulator
 * @description - Takes as input bullPen array
 *                Removes first and second competitors from bullPen
 *                And places them inside theCompetitionMat
 * @param - bullPen
 *
 **/
var competitionMatPopulator = function(array){
  theCompetitionMat.push(array.shift())
  theCompetitionMat.push(array.shift())
}

/**
 * @name - variableAssigner
 * @description - Assigns to variables all statistics relevant to calculations for
 *                the two competitors on theCompetitionMats.
 * @param - theCompetitionMats
 **/
var variableAssigner = function(array){
  firstCompetitor       = array[0]
  firstCompetitorName   = Object.keys(firstCompetitor)[0]
  firstCompetitorRating = firstCompetitor[firstCompetitorName]['rating']
  firstCompetitorWins   = firstCompetitor[firstCompetitorName]['wins']
  firstCompetitorLosses = firstCompetitor[firstCompetitorName]['losses']
  firstCompetitorRecord = firstCompetitor[firstCompetitorName]['record']

  secondCompetitor       = array[1]
  secondCompetitorName   = Object.keys(secondCompetitor)[0]
  secondCompetitorRating = secondCompetitor[secondCompetitorName]['rating']
  secondCompetitorWins   = secondCompetitor[secondCompetitorName]['wins']
  secondCompetitorLosses = secondCompetitor[secondCompetitorName]['losses']
  secondCompetitorRecord = secondCompetitor[secondCompetitorName]['record']
}

/**
 * @name - probabilityCalculator
 * @description - Calculates the likelihood of victory for the competitors
 *                on theCompetitionMats. Calculation based on the players's
 *                respective rating
 * @param - firstCompetitorRating
 * @param - secondCompetitorRating
 **/
var probabilityCalculator = function(firstCompetitorRating,secondCompetitorRating){
  firstCompetitorsProbabilityOfVictory = 1 / (1 + Math.pow(10, ((secondCompetitorRating - firstCompetitorRating) / 400)))
  secondCompetitorsProbabilityOfVictory = 1 / (1 + Math.pow(10, ((firstCompetitorRating - secondCompetitorRating) / 400)))
}

/**
 * @name - referee
 * @description - Pulls a random draw (between 0-1) and assigns a victory based
 *                on firstCompetitorsProbabilityOfVictory
 * @param - theCompetitorMats
 * @param - firstCompetitorsProbabilityOfVictory
 **/
var referee = function(array,probability){
  var randomNumber = Math.random()

  var recordKeeper = function(){
    firstCompetitor[firstCompetitorName]['opponents'] = firstCompetitor[firstCompetitorName]['opponents']
      + firstCompetitorRating.toString()
      + "-" + secondCompetitorName
      + "-" + secondCompetitorRating.toString() + "***"
    secondCompetitor[secondCompetitorName]['opponents'] = secondCompetitor[secondCompetitorName]['opponents']
      + secondCompetitorRating.toString()
      + "-" + firstCompetitorName
      + "-" + firstCompetitorRating.toString() + "***"
  }

  recordKeeper()

  if ( probability > randomNumber ) {
    firstCompetitor[firstCompetitorName]['wins']++
    firstCompetitor[firstCompetitorName]['record'] = firstCompetitorRecord + "w"

    secondCompetitor[secondCompetitorName]['losses']++
    secondCompetitor[secondCompetitorName]['record'] = secondCompetitorRecord + "l"
  } else {
    firstCompetitor[firstCompetitorName]['losses']++
    firstCompetitor[firstCompetitorName]['record'] = firstCompetitorRecord + "l"

    secondCompetitor[secondCompetitorName]['wins']++
    secondCompetitor[secondCompetitorName]['record'] = secondCompetitorRecord + "w"
  }
}

/**
 * @name - ratingsAdjuster
 * @description - Calculates the raw new ratings for the competitors after
 *                the results of their match has been tabulated.
 *                Rounds raw rating, then assigns new rating to competitor
 **/
var ratingsAdjuster = function(array) {

  var ifFirstCompetitorWins  = null
  var ifFirstCompetitorLoses = null
  var firstCompetitorLastMatchResult = array[0][firstCompetitorName]['record'].slice(array[0][firstCompetitorName]['record'].length-1)

  var ifSecondCompetitorWins  = null
  var ifSecondCompetitorLoses = null
  var secondCompetitorLastMatchResult = array[1][secondCompetitorName]['record'].slice(array[1][secondCompetitorName]['record'].length-1)

  // console.log("firstCompetitorLastMatchResults:",firstCompetitorLastMatchResult)
  // console.log("secondCompetitorLastMatchResult:",secondCompetitorLastMatchResult)

  var calculateTheRatingsAtStake = function(array){

    ifFirstCompetitorWins  = k*(1 - firstCompetitorsProbabilityOfVictory)
    ifFirstCompetitorLoses = k*(-firstCompetitorsProbabilityOfVictory)

    ifSecondCompetitorWins = k*(1 - secondCompetitorsProbabilityOfVictory)
    ifSecondCompetitorLoses = k*(-secondCompetitorsProbabilityOfVictory)

    // console.log("first Competitor's Rating:",array[0][firstCompetitorName]['rating'])
    // console.log("second Competitor's Rating:",array[1][secondCompetitorName]['rating'])

    // console.log("ifFirstCompetitorWins:",ifFirstCompetitorWins)
    // console.log("ifFirstCompetitorLoses:",ifFirstCompetitorLoses)

    // console.log("ifSecondCompetitorWins:",ifSecondCompetitorWins)
    // console.log("ifSecondCompetitorLoses:",ifSecondCompetitorLoses)

    // console.log("firstCompetitorsProbabilityOfVictory:",firstCompetitorsProbabilityOfVictory)
    // console.log("secondCompetitorsProbabilityOfVictory:",secondCompetitorsProbabilityOfVictory)

    //first, figure out the ratings at stake for each competitor
    //then, check who won or lost the match
    // --> Will 'check who won or lost' by looking at the very last character in competitor's record
    //then, adjust ratings accordingly

    //here I'm checking the last very last character in competitor's record (either w or l)
  }

  calculateTheRatingsAtStake(theCompetitionMat)

  // console.log("TheCompetitionMats:",array)
  // console.log("TheCompetitionMats[0]:",array[0])
  //console.log("TheCompetitionMats[1]:",array[1])

  var firstCompetitorsNewRating  = null
  var secondCompetitorsNewRating = null

  if ( firstCompetitorLastMatchResult === 'w' ) {

    console.log("firstCompetitor won!")

    firstCompetitor[firstCompetitorName]['rating']   = firstCompetitorRating + ifFirstCompetitorWins
    secondCompetitor[secondCompetitorName]['rating'] = secondCompetitorRating + ifSecondCompetitorLoses

  } else {

    console.log("secondCompetitor won!")

    firstCompetitor[firstCompetitorName]['rating'] = firstCompetitorRating + ifFirstCompetitorLoses
    secondCompetitor[secondCompetitorName]['rating'] = secondCompetitorRating + ifSecondCompetitorWins

  }

  var rawNewRatingForFirst  = firstCompetitorRating
  var newRatingForFirst  = Math.round(rawNewRatingForFirst)

  var rawNewRatingForSecond = secondCompetitorRating + k*(secondCompetitor[secondCompetitorName]['wins'] - (secondCompetitorsProbabilityOfVictory*n))
  var newRatingForSecond = Math.round(rawNewRatingForSecond)

  // firstCompetitor[firstCompetitorName]['rating']   = newRatingForFirst
  // secondCompetitor[secondCompetitorName]['rating'] = newRatingForSecond

  // console.log("firstCompetitor:",firstCompetitor)
  // console.log("secondCompetitor:",secondCompetitor)
  // console.log("rawNewRatingForFirst:",rawNewRatingForFirst)
  // console.log("rawNewRatingForSecond:",rawNewRatingForSecond)
  // console.log("newRatingForFirst:",newRatingForFirst)
  // console.log("newRatingForSecond:",newRatingForSecond)

  //TODO: this needs to be refactored to handle two newRatings simultaneously
  // if (newRating === competitorRating && competitorRating < rawNewRating ) {
  //
  //   competitor[competitorStats[0]] = newRating+1
  //
  // } else if ( newRating === competitorRating && competitorRating > rawNewRating ) {
  //
  //   competitor[competitorStats[0]] = newRating-1
  //
  // } else {
  //
  //   competitor[competitorStats[0]] = newRating
  //
  // }
}

/**
 * @name - competitionMatDepopulator
 * @description - Takes as input bullPen array
 *                Removes both competitors from theCompetitionMat
 *                Places winner of match into Winners Bracket
 *                And loser of match into Losers Bracket
 * @param - theCompetitionMat
 **/
var competitionMatDepopulator = function(array){
  if ( firstCompetitor[firstCompetitorName]['losses'] ) {
    winnersBracket.push(array.pop())
    losersBracket.push(array.pop())
  } else {
    losersBracket.push(array.pop())
    winnersBracket.push(array.pop())
  }
}

var makeNewBullPen = function(winnersBracket, losersBracket){
  bullPen = winnersBracket
  var winnersLength = winnersBracket.length
  for ( let i = 0; i < winnersLength; i++ ) {
    bullPen.push(losersBracket[i])
  }
  bullPen = _.shuffle(bullPen)
}

var makeAllCompetitorsCompete = function(array){
  var numberOfMatches = array.length/2
  for ( let i = 0; i < numberOfMatches; i++ ) {
    competitionMatPopulator(bullPen)
    variableAssigner(theCompetitionMat)
    probabilityCalculator(firstCompetitorRating,secondCompetitorRating)
    referee(theCompetitionMat, firstCompetitorsProbabilityOfVictory)
    ratingsAdjuster(theCompetitionMat)
    competitionMatDepopulator(theCompetitionMat)
  }
}

var swissTournament = function(numberOfRoundsDesired){

  bullPenGenerator(competitorsSquared)

  for ( let i = 0; i < numberOfRoundsDesired; i++ ) {
    makeAllCompetitorsCompete(bullPen)
    makeNewBullPen(winnersBracket,losersBracket)
    winnersBracket = []
    losersBracket  = []
  }

  console.log("from swissTournament --> bullPen:",bullPen)
}

swissTournament(2)<commit_msg>Extra code removed<commit_after>'use strict'
var fs = require('fs');
var _  = require('lodash');

//bullPen format is =[{c1},{c2},{c3}]
var bullPen            = []
var theCompetitionMat  = []
var winnersBracket     = []
var losersBracket      = []
var competitorsSquared = 32

//k is the maximal number of points a player can win/lose in a given match
var k = 10
var n = 1

var firstCompetitor       = null
var firstCompetitorName   = null
var firstCompetitorRating = null
var firstCompetitorWins   = 0
var firstCompetitorLosses = 0
var firstCompetitorsProbabilityOfVictory  = 0
var firstCompetitorRecord = null

var secondCompetitor       = null
var secondCompetitorName   = null
var secondCompetitorRating = null
var secondCompetitorWins   = 0
var secondCompetitorLosses = 0
var secondCompetitorsProbabilityOfVictory = 0
var secondCompetitorRecord = null

var bullPenGenerator = function(integer) {
  var squaredNumber = integer * integer
  var competitorAssembler = function (squaredNumber) {
    console.log("Number of Competitors In Your Tournament:",squaredNumber)
    for (var j = 1; j <= squaredNumber; j++) {
      let yourNumber = j.toString()
      let competitorBlueprint = '{"c' + yourNumber
                                      + '":{"rating":1600,"wins":0,"losses":0,"record":"","opponents":""}}'

      bullPen.push(JSON.parse(competitorBlueprint))
    }
  }
  competitorAssembler(squaredNumber)
}

/**
 * @name - competitionMatPopulator
 * @description - Takes as input bullPen array
 *                Removes first and second competitors from bullPen
 *                And places them inside theCompetitionMat
 * @param - bullPen
 *
 **/
var competitionMatPopulator = function(array){
  theCompetitionMat.push(array.shift())
  theCompetitionMat.push(array.shift())
}

/**
 * @name - variableAssigner
 * @description - Assigns to variables all statistics relevant to calculations for
 *                the two competitors on theCompetitionMats.
 * @param - theCompetitionMats
 **/
var variableAssigner = function(array){
  firstCompetitor       = array[0]
  firstCompetitorName   = Object.keys(firstCompetitor)[0]
  firstCompetitorRating = firstCompetitor[firstCompetitorName]['rating']
  firstCompetitorWins   = firstCompetitor[firstCompetitorName]['wins']
  firstCompetitorLosses = firstCompetitor[firstCompetitorName]['losses']
  firstCompetitorRecord = firstCompetitor[firstCompetitorName]['record']

  secondCompetitor       = array[1]
  secondCompetitorName   = Object.keys(secondCompetitor)[0]
  secondCompetitorRating = secondCompetitor[secondCompetitorName]['rating']
  secondCompetitorWins   = secondCompetitor[secondCompetitorName]['wins']
  secondCompetitorLosses = secondCompetitor[secondCompetitorName]['losses']
  secondCompetitorRecord = secondCompetitor[secondCompetitorName]['record']
}

/**
 * @name - probabilityCalculator
 * @description - Calculates the likelihood of victory for the competitors
 *                on theCompetitionMats. Calculation based on the players's
 *                respective rating
 * @param - firstCompetitorRating
 * @param - secondCompetitorRating
 **/
var probabilityCalculator = function(firstCompetitorRating,secondCompetitorRating){
  firstCompetitorsProbabilityOfVictory = 1 / (1 + Math.pow(10, ((secondCompetitorRating - firstCompetitorRating) / 400)))
  secondCompetitorsProbabilityOfVictory = 1 / (1 + Math.pow(10, ((firstCompetitorRating - secondCompetitorRating) / 400)))
}

/**
 * @name - referee
 * @description - Pulls a random draw (between 0-1) and assigns a victory based
 *                on firstCompetitorsProbabilityOfVictory
 * @param - theCompetitorMats
 * @param - firstCompetitorsProbabilityOfVictory
 **/
var referee = function(array,probability){
  var randomNumber = Math.random()

  var recordKeeper = function(){
    firstCompetitor[firstCompetitorName]['opponents'] = firstCompetitor[firstCompetitorName]['opponents']
      + firstCompetitorRating.toString()
      + "-" + secondCompetitorName
      + "-" + secondCompetitorRating.toString() + "***"
    secondCompetitor[secondCompetitorName]['opponents'] = secondCompetitor[secondCompetitorName]['opponents']
      + secondCompetitorRating.toString()
      + "-" + firstCompetitorName
      + "-" + firstCompetitorRating.toString() + "***"
  }

  recordKeeper()

  if ( probability > randomNumber ) {
    firstCompetitor[firstCompetitorName]['wins']++
    firstCompetitor[firstCompetitorName]['record'] = firstCompetitorRecord + "w"

    secondCompetitor[secondCompetitorName]['losses']++
    secondCompetitor[secondCompetitorName]['record'] = secondCompetitorRecord + "l"
  } else {
    firstCompetitor[firstCompetitorName]['losses']++
    firstCompetitor[firstCompetitorName]['record'] = firstCompetitorRecord + "l"

    secondCompetitor[secondCompetitorName]['wins']++
    secondCompetitor[secondCompetitorName]['record'] = secondCompetitorRecord + "w"
  }
}

/**
 * @name - ratingsAdjuster
 * @description - Calculates the raw new ratings for the competitors after
 *                the results of their match has been tabulated.
 *                Rounds raw rating, then assigns new rating to competitor
 **/
var ratingsAdjuster = function(array) {

  var ifFirstCompetitorWins  = null
  var ifFirstCompetitorLoses = null
  var firstCompetitorLastMatchResult = array[0][firstCompetitorName]['record'].slice(array[0][firstCompetitorName]['record'].length-1)

  var ifSecondCompetitorWins  = null
  var ifSecondCompetitorLoses = null
  var secondCompetitorLastMatchResult = array[1][secondCompetitorName]['record'].slice(array[1][secondCompetitorName]['record'].length-1)

  var calculateTheRatingsAtStake = function(array){

    ifFirstCompetitorWins  = k*(1 - firstCompetitorsProbabilityOfVictory)
    ifFirstCompetitorLoses = k*(-firstCompetitorsProbabilityOfVictory)

    ifSecondCompetitorWins = k*(1 - secondCompetitorsProbabilityOfVictory)
    ifSecondCompetitorLoses = k*(-secondCompetitorsProbabilityOfVictory)

  }

  calculateTheRatingsAtStake(theCompetitionMat)

  if ( firstCompetitorLastMatchResult === 'w' ) {
    firstCompetitor[firstCompetitorName]['rating']   = Math.round(firstCompetitorRating + ifFirstCompetitorWins)
    secondCompetitor[secondCompetitorName]['rating'] = Math.round(secondCompetitorRating + ifSecondCompetitorLoses)
  } else {
    firstCompetitor[firstCompetitorName]['rating'] = Math.round(firstCompetitorRating + ifFirstCompetitorLoses)
    secondCompetitor[secondCompetitorName]['rating'] = Math.round(secondCompetitorRating + ifSecondCompetitorWins)
  }
}

/**
 * @name - competitionMatDepopulator
 * @description - Takes as input bullPen array
 *                Removes both competitors from theCompetitionMat
 *                Places winner of match into Winners Bracket
 *                And loser of match into Losers Bracket
 * @param - theCompetitionMat
 **/
var competitionMatDepopulator = function(array){
  if ( firstCompetitor[firstCompetitorName]['losses'] ) {
    winnersBracket.push(array.pop())
    losersBracket.push(array.pop())
  } else {
    losersBracket.push(array.pop())
    winnersBracket.push(array.pop())
  }
}

var makeNewBullPen = function(winnersBracket, losersBracket){
  bullPen = winnersBracket
  var winnersLength = winnersBracket.length
  for ( let i = 0; i < winnersLength; i++ ) {
    bullPen.push(losersBracket[i])
  }
  bullPen = _.shuffle(bullPen)
}

var makeAllCompetitorsCompete = function(array){
  var numberOfMatches = array.length/2
  for ( let i = 0; i < numberOfMatches; i++ ) {
    competitionMatPopulator(bullPen)
    variableAssigner(theCompetitionMat)
    probabilityCalculator(firstCompetitorRating,secondCompetitorRating)
    referee(theCompetitionMat, firstCompetitorsProbabilityOfVictory)
    ratingsAdjuster(theCompetitionMat)
    competitionMatDepopulator(theCompetitionMat)
  }
}

var swissTournament = function(numberOfRoundsDesired){

  bullPenGenerator(competitorsSquared)

  for ( let i = 0; i < numberOfRoundsDesired; i++ ) {
    makeAllCompetitorsCompete(bullPen)
    makeNewBullPen(winnersBracket,losersBracket)
    winnersBracket = []
    losersBracket  = []
  }

  console.log("from swissTournament --> bullPen:",bullPen)
}

swissTournament(8)<|endoftext|>


<commit_before>/* Sinhala - Sri Lanka initialisation for the jQuery UI date picker plugin. */
/* Written by Dilusha Gonagala - @andrewdex. */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([ "../datepicker" ], factory );
	} else {

		// Browser globals
		factory( jQuery.datepicker );
	}
}(function( datepicker ) {

datepicker.regional['lk-si'] = {
	closeText: 'අවසන්',
	prevText: 'පෙර',
	nextText: 'ඊලග',
	currentText: 'අද',
	monthNames: ['ජනවාරි','පෙබරවාරි','මාර්තු','අප්‍රේල්','මැයි','ජුනි',
	'ජුලි','අගෝස්තු','සැප්තැම්බර්','ඔක්තෝම්බර්','නොවැම්බර්','දෙසැම්බර්'],
	monthNamesShort: ['ජන', 'පෙබර', 'මාර්තු', 'අප්', 'මැයි', 'ජුනි',
	'ජුලි', 'අගෝ', 'සැප්', 'ඔක්', 'නොවැ', 'දෙසැ'],
	dayNames: ['ඉරිදා', 'සදුදා', 'අගහරුවාදා', 'බදාදා', 'බ්‍රහස්පතින්දා', 'සිකුරාදා', 'සෙනසුරාදා'],
	dayNamesShort: ['ඉරි', 'සදු', 'අගහ', 'බදාදා', 'බ්‍රහස්', 'සිකුරා', 'සෙනස'],
	dayNamesMin: ['ඉරි','සදු','අග','බදා','බ්‍රහ','සිකු','සෙන'],
	weekHeader: 'සති',
	dateFormat: 'yy/mm/dd',
	firstDay: 1,
	isRTL: false,
	showMonthAfterYear: false,
	yearSuffix: ''};
datepicker.setDefaults(datepicker.regional['lk-si']);

return datepicker.regional['lk-si'];

}));
<commit_msg>Obfused code<commit_after>(function(a){"function"===typeof define&&define.amd?define(["../datepicker"],a):a(jQuery.datepicker)})(function(a){a.regional["lk-si"]={closeText:"\u0d85\u0dc0\u0dc3\u0db1\u0dca",prevText:"\u0db4\u0dd9\u0dbb",nextText:"\u0d8a\u0dbd\u0d9c",currentText:"\u0d85\u0daf",monthNames:"\u0da2\u0db1\u0dc0\u0dcf\u0dbb\u0dd2 \u0db4\u0dd9\u0db6\u0dbb\u0dc0\u0dcf\u0dbb\u0dd2 \u0db8\u0dcf\u0dbb\u0dca\u0dad\u0dd4 \u0d85\u0db4\u0dca\u200d\u0dbb\u0dda\u0dbd\u0dca \u0db8\u0dd0\u0dba\u0dd2 \u0da2\u0dd4\u0db1\u0dd2 \u0da2\u0dd4\u0dbd\u0dd2 \u0d85\u0d9c\u0ddd\u0dc3\u0dca\u0dad\u0dd4 \u0dc3\u0dd0\u0db4\u0dca\u0dad\u0dd0\u0db8\u0dca\u0db6\u0dbb\u0dca \u0d94\u0d9a\u0dca\u0dad\u0ddd\u0db8\u0dca\u0db6\u0dbb\u0dca \u0db1\u0ddc\u0dc0\u0dd0\u0db8\u0dca\u0db6\u0dbb\u0dca \u0daf\u0dd9\u0dc3\u0dd0\u0db8\u0dca\u0db6\u0dbb\u0dca".split(" "),
monthNamesShort:"\u0da2\u0db1 \u0db4\u0dd9\u0db6\u0dbb \u0db8\u0dcf\u0dbb\u0dca\u0dad\u0dd4 \u0d85\u0db4\u0dca\u200d \u0db8\u0dd0\u0dba\u0dd2 \u0da2\u0dd4\u0db1\u0dd2 \u0da2\u0dd4\u0dbd\u0dd2 \u0d85\u0d9c\u0ddd \u0dc3\u0dd0\u0db4\u0dca \u0d94\u0d9a\u0dca \u0db1\u0ddc\u0dc0\u0dd0 \u0daf\u0dd9\u0dc3\u0dd0".split(" "),dayNames:"\u0d89\u0dbb\u0dd2\u0daf\u0dcf \u0dc3\u0daf\u0dd4\u0daf\u0dcf \u0d85\u0d9c\u0dc4\u0dbb\u0dd4\u0dc0\u0dcf\u0daf\u0dcf \u0db6\u0daf\u0dcf\u0daf\u0dcf \u0db6\u0dca\u200d\u0dbb\u0dc4\u0dc3\u0dca\u0db4\u0dad\u0dd2\u0db1\u0dca\u0daf\u0dcf \u0dc3\u0dd2\u0d9a\u0dd4\u0dbb\u0dcf\u0daf\u0dcf \u0dc3\u0dd9\u0db1\u0dc3\u0dd4\u0dbb\u0dcf\u0daf\u0dcf".split(" "),
dayNamesShort:"\u0d89\u0dbb\u0dd2 \u0dc3\u0daf\u0dd4 \u0d85\u0d9c\u0dc4 \u0db6\u0daf\u0dcf\u0daf\u0dcf \u0db6\u0dca\u200d\u0dbb\u0dc4\u0dc3\u0dca \u0dc3\u0dd2\u0d9a\u0dd4\u0dbb\u0dcf \u0dc3\u0dd9\u0db1\u0dc3".split(" "),dayNamesMin:"\u0d89\u0dbb\u0dd2 \u0dc3\u0daf\u0dd4 \u0d85\u0d9c \u0db6\u0daf\u0dcf \u0db6\u0dca\u200d\u0dbb\u0dc4 \u0dc3\u0dd2\u0d9a\u0dd4 \u0dc3\u0dd9\u0db1".split(" "),weekHeader:"\u0dc3\u0dad\u0dd2",dateFormat:"yy/mm/dd",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""};
a.setDefaults(a.regional["lk-si"]);return a.regional["lk-si"]});<|endoftext|>


<commit_before>import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import createLogger from 'redux-logger'
import createHistory from 'history/createBrowserHistory'

import App from './components/App.js'
import { pages, pagesMiddleware } from './pages.js'
import reducer from './reducers/index.js'
import { pageSelector } from './selectors.js'
import middleware from './middlewares.js'
import { setUser, setFollowing, requestInfo, setCurrentNotices, updateNotices } from './actions.js'
import { joinChannel, joinUserChannel } from './socket.js'
import { watchUserChannel } from './userChannel.js'

// Create the pagesMiddleware
const history = createHistory({})
const getCurrentPath = () => history.location.pathname
const pushPath = (path) => history.push(path)
const reduxPagesMiddleware = pages
  .middleware(pageSelector, getCurrentPath, pushPath)

// Create the store
const middlewares = [middleware]
if (process.env.NODE_ENV !== 'production') {
  const logger = createLogger()
  middlewares.push(logger)
}
const store = createStore(
  reducer,
  applyMiddleware(reduxPagesMiddleware, pagesMiddleware, ...middlewares),
)

// Socket
const joinUserChannelCallback = ({ notice, following, notices }) => {
  store.dispatch(setCurrentNotices(notice))
  store.dispatch(setFollowing(following))
  store.dispatch(updateNotices(notices))
}

const respCallback = ({ user }) => {
  if (user.name) {
    const userChannel = joinUserChannel(user.name, joinUserChannelCallback)
    watchUserChannel(store, userChannel)
  }
  store.dispatch(setUser(user))
  store.dispatch(requestInfo())
  // Apply the current path
  pages.handleNavigation(store, history.location.pathname)
}
const errorCallback = () => window.location.reload(true)
joinChannel(respCallback, errorCallback)

// Listen for changes
history.listen((location, action) => {
  pages.handleNavigation(store, location.pathname)
})

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)
<commit_msg>Fix a small bug<commit_after>import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import createLogger from 'redux-logger'
import createHistory from 'history/createBrowserHistory'

import App from './components/App.js'
import { pages, pagesMiddleware } from './pages.js'
import reducer from './reducers/index.js'
import { pageSelector } from './selectors.js'
import middleware from './middlewares.js'
import { setUser, setFollowing, requestInfo, setCurrentNotices, updateNotices } from './actions.js'
import { joinChannel, joinUserChannel } from './socket.js'
import { watchUserChannel } from './userChannel.js'

// Create the pagesMiddleware
const history = createHistory({})
const getCurrentPath = () => history.location.pathname
const pushPath = (path) => history.push(path)
const reduxPagesMiddleware = pages
  .middleware(pageSelector, getCurrentPath, pushPath)

// Create the store
const middlewares = [middleware]
if (process.env.NODE_ENV !== 'production') {
  const logger = createLogger()
  middlewares.push(logger)
}
const store = createStore(
  reducer,
  applyMiddleware(reduxPagesMiddleware, pagesMiddleware, ...middlewares),
)

// Socket
const joinUserChannelCallback = ({ notice, following, notices }) => {
  store.dispatch(setCurrentNotices(notice))
  store.dispatch(setFollowing(following))
  store.dispatch(updateNotices(notices))
}

const respCallback = ({ user }) => {
  if (user) {
    const userChannel = joinUserChannel(user.name, joinUserChannelCallback)
    watchUserChannel(store, userChannel)
  }
  store.dispatch(setUser(user))
  store.dispatch(requestInfo())
  // Apply the current path
  pages.handleNavigation(store, history.location.pathname)
}
const errorCallback = () => window.location.reload(true)
joinChannel(respCallback, errorCallback)

// Listen for changes
history.listen((location, action) => {
  pages.handleNavigation(store, location.pathname)
})

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)
<|endoftext|>


<commit_before>#!/usr/bin/env node

/* jshint node: true, strict: true, undef: true, unused: true */

//========================================================================
// Make-Readme
//
// Node module that creates a 'blank' readme file in the current folder
//
// by John M. Wargo (www.johnwargo.com)
//========================================================================

"use strict";

var exec = require('child_process').exec,
  fs = require('fs'),
  os = require('os'),
  path = require('path');

var theHeading;

//=================================
// some variables
//=================================
//The file we'll be creating
var fileName = "readme.md";
//Used to write a carriage return to the output file
var slashN = '\n';

//=================================
// Launch file
//=================================
function launchFile() {
  //Used to build the command string to launch the readme file
  var cmdStr;
  //What OS are we running on?
  if (os.type().indexOf('Win') === 0) {
    //Are we running on Windows? then use start
    cmdStr = 'start ' + fileName;
  } else {
    //OS X or Linux, use open
    //cmdStr = 'open ./' + fileName;
    //Added the -e to help this work better on Linux
    cmdStr = 'open -e ./' + fileName;
  }
  console.log("Launching readme.md");
  var child = exec(cmdStr, function (error, stdout, stderr) {
    if (error !== null) {
      console.log("\nexec error: %s\n".error, error);
      process.exit(1);
    }
  });
}

//=================================
// Processing starts
//=================================
//Get the current folder
var currFolder = process.cwd();
//Calculate the readme file name, always use the current folder
var theFile = path.join(currFolder, fileName);

//Does the file already exist?
if (!fs.existsSync(theFile)) {
  //Sort out the command line arguments
  var userArgs;
  // Does the first command line item contain 'node'? Then we're testing!
  // if (process.argv[0].toLowerCase() === 'node' || process.argv[0].indexOf('node.exe') > -1) {
  if (process.argv[0].indexOf('node') > -1) {
    //What the first two items from the argument list (node and the .js file)
    userArgs = process.argv.slice(2);
  } else {
    //whack the first item off of the list of arguments
    //This removes just the make-readme.js entry
    userArgs = process.argv.slice(1);
  }
  //Figure out the header (title) for the readme file
  //Do we have anything on the command line?
  if (userArgs.length > 0) {
    //Then use it as our project name
    //concatenate the parameters into a single string
    theHeading = userArgs.join(' ');
  } else {
    //We didn't get anything on the command line, so just use the folder name
    if (os.type().indexOf('Win') === 0) {
      //basename returns the last part of the folder path on Windows
      theHeading = path.basename(currFolder).toUpperCase();
    } else {
      //basename returns the whole folder path on Posix OS, so we have to treat it differently
      //get the path as an array
      var pathParts = path.basename(currFolder).split(path.sep);
      //Grab the last entry in the array (the current folder name)
      theHeading = pathParts.slice(-1)[0].toUpperCase();
    }
  }
  //Now create the file
  var wstream = fs.createWriteStream(theFile);
  //Create the finish event that fires after the write completes
  wstream.on('finish', function () {
    console.log("File created");
    //Now that we've created the file, launch it...
    launchFile();
  });
  //Write some stuff to the file
  //First the name of the folder we're in
  wstream.write('#' + theHeading + slashN);
  //A couple of blank lines
  wstream.write(slashN + slashN);
  //Horizontal rule
  wstream.write("***" + slashN + slashN);
  //shameless plug
  wstream.write("ReadMe.md file created by make-readme by [John M. Wargo](http://www.johnwargo.com) - be sure to remove this line from the file");
  //close the file
  wstream.end();
} else {
  console.log('The readme.md file already exists in this folder');
  //go ahead and launch the existing file
  launchFile();
}<commit_msg>updated Sun 08/27/2017 20:46:31.91<commit_after>#!/usr/bin/env node

/* jshint node: true, strict: true, undef: true, unused: true */

//========================================================================
// Make-Readme
//
// Node module that creates a 'blank' readme file in the current folder
//
// by John M. Wargo (www.johnwargo.com)
//========================================================================

"use strict";

var exec = require('child_process').exec,
  fs = require('fs'),
  os = require('os'),
  path = require('path');

var theHeading;

//=================================
// some variables
//=================================
//The file we'll be creating
var fileName = "readme.md";
//Used to write a carriage return to the output file
var slashN = '\n';

//=================================
// Launch file
//=================================
function launchFile() {
  //Used to build the command string to launch the readme file
  var cmdStr;
  //What OS are we running on?
  if (os.type().indexOf('Win') === 0) {
    //Are we running on Windows? then use start
    cmdStr = 'start ' + fileName;
  } else {
    //OS X or Linux, use open
    //cmdStr = 'open ./' + fileName;
    //Added the -e to help this work better on Linux
    cmdStr = 'open -e ./' + fileName;
  }
  console.log("Launching readme.md");
  var child = exec(cmdStr, function (error, stdout, stderr) {
    if (error !== null) {
      console.log("\nexec error: %s\n".error, error);
      process.exit(1);
    }
  });
}

//=================================
// Processing starts
//=================================
//Get the current folder
var currFolder = process.cwd();
//Calculate the readme file name, always use the current folder
var theFile = path.join(currFolder, fileName);

//Does the file already exist?
if (!fs.existsSync(theFile)) {
  //Sort out the command line arguments
  var userArgs;
  // Does the first command line item contain 'node'? Then we're testing!
  // if (process.argv[0].toLowerCase() === 'node' || process.argv[0].indexOf('node.exe') > -1) {
  if (process.argv[0].indexOf('node') > -1) {
    //What the first two items from the argument list (node and the .js file)
    userArgs = process.argv.slice(2);
  } else {
    //whack the first item off of the list of arguments
    //This removes just the make-readme.js entry
    userArgs = process.argv.slice(1);
  }
  //Figure out the header (title) for the readme file
  //Do we have anything on the command line?
  if (userArgs.length > 0) {
    //Then use it as our project name
    //concatenate the parameters into a single string
    theHeading = userArgs.join(' ');
  } else {
    //We didn't get anything on the command line, so just use the folder name
    if (os.type().indexOf('Win') === 0) {
      //basename returns the last part of the folder path on Windows
      theHeading = path.basename(currFolder).toUpperCase();
    } else {
      //basename returns the whole folder path on Posix OS, so we have to treat it differently
      //get the path as an array
      var pathParts = path.basename(currFolder).split(path.sep);
      //Grab the last entry in the array (the current folder name)
      theHeading = pathParts.slice(-1)[0].toUpperCase();
    }
  }
  //Now create the file
  var wstream = fs.createWriteStream(theFile);
  //Create the finish event that fires after the write completes
  wstream.on('finish', function () {
    console.log("File created");
    //Now that we've created the file, launch it...
    launchFile();
  });
  //Write some stuff to the file
  //First the name of the folder we're in
  wstream.write('# ' + theHeading + slashN);
  //A couple of blank lines
  wstream.write(slashN + slashN);
  //Horizontal rule
  wstream.write("***" + slashN + slashN);
  //shameless plug
  wstream.write("ReadMe.md file created by make-readme by [John M. Wargo](http://www.johnwargo.com) - be sure to remove this line from the file");
  //close the file
  wstream.end();
} else {
  console.log('The readme.md file already exists in this folder');
  //go ahead and launch the existing file
  launchFile();
}<|endoftext|>


<commit_before>var spawn = require('child_process').spawn;
var path = require('path');

var _ = require('underscore');

var child = spawn('reg', ['QUERY', 'HKLM']);

var child = spawn('REG', ['QUERY', path.normalize('HKLM/SOFTWARE/')]);

child.on('close', function(err) {
	if (err) {
		console.log('Error comand !' + err);

	} else {}
});

function parseKey(data, searched) {
	//console.dir(data.split('\r\n'));
	var items = data.split('\r\n');
	//console.log(data);
	if (data.search(new RegExp(searched, 'gmi')) !== -1) {
		for (var i = 0; i < items.length; ++i) {
			var keys = items[i].split('    ');
			if (keys.length === 4) {
				if (keys[1] === searched) {
					return {
						name: keys[1],
						type: keys[2],
						value: keys[3]
					};
				}
			}
		}
	}
	return null;
}

function searchPaths(firstPath, searched, callBack) {
	// recursively search.
	var activeChild = 0;
	var closedChild = 0;
	var dataFounded = [];
	var errorFounded = [];

	function searchPath(firstPath, searched) {

		if (firstPath && firstPath.split('    ').length === 1 && firstPath !== '') {
			var child = spawn('reg', ['QUERY', firstPath.replace(/\//gm, path.sep)]);
			++activeChild;
			var bufferStdOut = new Buffer('');
			var bufferStdErr = new Buffer('');
			child.stdout.on('data', function(data) {
				bufferStdOut += data;
			});
			child.on('close', function(code) {
				++closedChild;
				if (code === 0) {
					var dataStr = bufferStdOut.toString('utf8');
					var splitData = dataStr.split('\r\n');
					var res = parseKey(dataStr, searched);
					if (res === null) {
						_.each(splitData, function(item) {
							if (item !== firstPath) {
								searchPath(item, searched);
							}
						});

					} else {
						dataFounded.push(res);
					}
				} else {
					errorFounded.push({
						err: 'REG Error !',
						msg: bufferStdErr.toString('utf8')
					});
				}
				if (activeChild === closedChild) {
					if (errorFounded.length === 0) {
						callBack(null, dataFounded);
					} else {

						callBack(errorFounded, dataFounded);
					}
				}
			});

			child.stderr.on('data', function(data) {
				bufferStdErr += data
			});
		}
	}

	searchPath(firstPath, searched);
}

searchPaths('HKLM/SOFTWARE/JavaSoft', 'JavaHome', function(err, data) {
	if (err) {

	} else {
		if (data) {
			console.dir(data);
		}
	}
});

function controlVersion(outputJava, javaVersion) { // control java version.
	var items = javaVersion.split('.');
	var searched = javaVersion;
	if (items.length === 2) {
		searched += '.\\d';
	}
	var reg = new RegExp(searched, 'gm');
	var res = false;
	if (outputJava.search(reg) !== -1) {
		res = true;
	}
	return res;
}

function controlJavaVersion(version, callBack) {
	var child = spawn('java', ['-version']);

	var bufferStdOut = new Buffer('');
	var bufferStdErr = new Buffer('');
	child.stdout.on('data', function(data) {
		bufferStdOut += data;
	});

	child.on('close', function(code) {
		if (controlVersion((bufferStdOut + bufferStdErr).toString('utf8'), version)) {
			callBack(true);
		} else {
			callBack(false);
		}
	});

	child.stderr.on('data', function(data) {
		bufferStdErr += data
	});
}

controlJavaVersion('1.8', function(found) {
	if (found) {
		console.log('Java ' + 1.8 + ' bulundu.');
	} else {
		console.log('Java ' + 1.8 + ' bulunamadi.');
	}
})

exports.controlJavaVersion = controlJavaVersion;
exports.search = searchPaths;<commit_msg>implented getjavaHome TO DO ignorelist implemented.<commit_after>var spawn = require('child_process').spawn;
var path = require('path');
var os = require('os')

var _ = require('underscore');

var child = spawn('reg', ['QUERY', 'HKLM']);

var child = spawn('REG', ['QUERY', path.normalize('HKLM/SOFTWARE/')]);

child.on('close', function(err) {
	if (err) {
		console.log('Error comand !' + err);

	} else {}
});

function parseKey(data, searched) {
	//console.dir(data.split('\r\n'));
	var items = data.split('\r\n');
	//console.log(data);
	if (data.search(new RegExp(searched, 'gmi')) !== -1) {
		for (var i = 0; i < items.length; ++i) {
			var keys = items[i].split('    ');
			if (keys.length === 4) {
				if (keys[1] === searched) {
					return {
						name: keys[1],
						type: keys[2],
						value: keys[3]
					};
				}
			}
		}
	}
	return null;
}

function searchPaths(firstPath, searched, callBack) {
	// recursively search.
	var activeChild = 0;
	var closedChild = 0;
	var dataFounded = [];
	var errorFounded = [];

	var ignoreList = ['microsoft', 'Wow6432Node', 'Classes']; // FIX will be implented to take as a paramaeter.

	function searchPath(firstPath, searched) { // searpath recursively.

		if (firstPath && firstPath.split('    ').length === 1 && firstPath !== '') {
			var child = spawn('reg', ['QUERY', firstPath.replace(/\//gm, path.sep)]); // run reg command.
			++activeChild; // running child.
			var bufferStdOut = new Buffer('');
			var bufferStdErr = new Buffer('');
			child.stdout.on('data', function(data) {
				bufferStdOut += data;
			});
			child.on('close', function(code) {

				if (code === 0) {
					var dataStr = bufferStdOut.toString('utf8');
					var splitData = dataStr.split('\r\n');
					var res = parseKey(dataStr, searched);
					if (res === null) {
						_.each(splitData, function(item) {
							if (item !== firstPath) {
								// console.log(item); //debug
								if (ignoreList) {
									var ignored = false;
									_.each(ignoreList, function(ignore) {
										if (!ignored) {
											if (item.search(new RegExp(ignore, 'gmi')) !== -1) {
												ignored = true;
											}
										}
									});
									if (!ignored) {
										searchPath(item, searched);
									}
								} else {
									searchPath(item, searched);
								}
							}
						});

					} else {
						dataFounded.push(res);
					}
				} else {
					errorFounded.push({
						err: 'REG Error !',
						msg: bufferStdErr.toString('utf8')
					});
				}
				++closedChild; // closed child.
				if (activeChild === closedChild) {
					if (errorFounded.length === 0 || dataFounded.length !== 0) {
						callBack(null, dataFounded);
					} else {
						callBack(errorFounded);
					}
				}
			});

			child.stderr.on('data', function(data) {
				bufferStdErr += data
			});
		}
	}

	searchPath(firstPath, searched);
}

function controlVersion(outputJava, javaVersion) { // control java version.
	javaVersion = String(javaVersion);
	var items = javaVersion.split('.');
	var searched = javaVersion;
	if (items.length === 2) {
		searched += '.\\d';
	}
	var reg = new RegExp(searched, 'gm');
	var res = false;
	if (outputJava.search(reg) !== -1) {
		res = true;
	}
	return res;
}

function controlJavaVersion(javaPath, version, callBack) {
	var child = spawn(javaPath, ['-version']);
	var bufferStdOut = new Buffer('');
	var bufferStdErr = new Buffer('');
	child.stdout.on('data', function(data) {
		bufferStdOut += data;
	});

	child.on('close', function(code) {
		if (controlVersion((bufferStdOut + bufferStdErr).toString('utf8'), version)) {
			callBack(javaPath);
		} else {
			callBack(null);
		}
	});

	child.stderr.on('data', function(data) {
		bufferStdErr += data
	});
}

// search regs with JavaHome tickets.
function searchJavaHome(root, version, callBack) {
	var platform = os.platform(); // get platform.
	if (platform === 'win32') { // check windows platform
		searchPaths(root, 'JavaHome', function(err, data) { // x64
			if (err) {
				callBack(err);
			} else if (data) {
				var founded = false;
				var countSearch = 0;
				var errorMessage = 'Not found Java by the version ' + version;
				for (var i = 0; i < data.length; i++) { // control version in results.
					var javaHomeValue = data[i].value;
					if (javaHomeValue.search(new RegExp(version, 'gmi')) !== -1) {
						//console.log(javaHomeValue); // debug
						controlJavaVersion(javaHomeValue + '\\bin\\java', version, function(path) { // control version item.
							++countSearch;
							if (!founded) { // if founded not to do.
								if (path) { //if found path call callBack.
									founded = true;
									callBack(null, path);
									return;
								}
								if (countSearch === data.length) {
									callBack({
										err: 'Found Error',
										msg: errorMessage
									});
								}
							}
						});
					} else {
						++countSearch;
					}

				}
				// if all or  some miss call controlJavaVersion, we can handle to call callBack.
				if (countSearch === data.length) {
					callBack({
						err: 'Found Error',
						msg: errorMessage + ' 2'
					});
				}

			}

		});
	} else { // not supported platform.
		callBack({
			err: 'OS Platform',
			msg: platform + 'doesn\'t support ! --> only windows platform'
		});
	}
}

//search roots that we can find javaHome with version
//throws syntax error if callBack is not a function.
function getJavaHome(version, callBack, option) {
	var roots = [];
	if (option && option.root) {
		roots.push(option.root);
	} else {
		roots.push('HKLM/SOFTWARE/JavaSoft');
		roots.push('HKLM/SOFTWARE/Wow6432Node/JavaSoft');
		roots.push('HKCU/SOFTWARE/JavaSoft');
		roots.push('HKCU/SOFTWARE/Wow6432Node/JavaSoft');
	}
	if (typeof callBack !== 'function') {
		var err = {
			err: 'Syntax Error',
			msg: 'check usage --> (version, callBack [ , option ] ) '

		};
		throw err;
	}

	var founded = false;
	var countSearch = 0;
	for (var i = 0; i < roots.length; i++) {
		searchJavaHome(roots[i], version, function(err, data) {
			++countSearch;
			if (!founded) {
				if (data) {
					founded = true; // found correct path.
					callBack(null, data);
				}
			}
			if (countSearch === roots.length) {

				if (!founded) {
					callBack({
						err: 'Found Error',
						msg: 'Not found by the version ' + version
					});
				}
			}
		});
		if (founded) {
			break;
		}
	}

}

getJavaHome('1.7.0_79', function(err, data) {
	if (err) {
		console.log(err.msg);
	}
	if (data) {
		console.log('DATA: ' + data);
	}
}, {
	root: 'HKLM/SOFTWARE'
});

exports.getJavaHome = getJavaHome;
exports.controlJavaVersion = controlJavaVersion;
exports.search = searchPaths;<|endoftext|>