<commit_before>/**
 *  KitScript - A User Script Safari Extension
 *
 *  Greasemonkey.js - Javascript file containing Greasemonkey classes
 *  (by Prototype.js) used globally in the extension & implementing core
 *  Greasemonkey API.
 *
 *  @author Seraf Dos Santos
 *  @copyright 2011-2012 Seraf Dos Santos - All rights reserved.
 *  @license MIT License
 *  @version 0.1
 */

/**
 *  KSGMUS (KitScript Greasemonkey User Script Class)
 */
var KSGMUS = Class.create({

    initialize: function (script) {

        this._script = script;
    },
    hasValidHeader: function () {

        var _isValid = /\/\/[ ]+==UserScript==\n.*\/\/[ ]+==\/UserScript==/g.test(this._script);

        return _isValid;
    },
    getIncludes: function () {

        var _includes = [];

        var matches = /\/\/[ ]+\@include (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _includes.push(matches[i]);
        }

        return _includes;
    },
    getExcludes: function () {

        var _excludes = [];

        var matches = /\/\/[ ]+\@exclude (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _excludes.push(matches[i]);
        }

        return _excludes;
    },
    getDescription: function () {

        var matches = /\/\/[ ]+\@description (.*)/g.exec(this._script);

        return matches[1];
    },
    getIcon: function () {

        var matches = /\/\/[ ]+\@icon (.*)/g.exec(this._script);

        return matches[1];
    },
    getMatches: function () {

        var _matches = [];

        var matches = /\/\/[ ]+\@match (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _matches.push(matches[i]);
        }

        return _matches;
    },
    getName: function () {

        var matches = /\/\/[ ]+\@name (.*)/g.exec(this._script);

        return matches[1];
    },
    getNamespace: function () {

        var matches = /\/\/[ ]+\@namespace (.*)/g.exec(this._script);

        return matches[1];
    },
    getRequires: function () {

        var _requires = [];

        var matches = /\/\/[ ]+\@match (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _requires.push(matches[i]);
        }

        return _requires;
    },
    getResources: function () {

        var _resources = [];

        var matches = /\/\/[ ]+\@resource (.*) (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _resources.push(new Array(matches[i], matches[i+1]));
        }

        return _resources;
    },
    getRunAt: function () {

        var matches = /\/\/[ ]+\@run-at (.*)/g.exec(this._script);

        return matches[1];
    },
    hasUnwrap: function () {

        var _hasUnwrap = /\/\/[ ]+\@unwrap (.*)/g.test(this._script);

        return _hasUnwrap;
    },
    getVersion: function () {

        var matches = /\/\/[ ]+\@version (.*)/g.exec(this._script);

        return matches[1];
    }
});

//
// Greasemonkey
//

/**
 *  @param string name
 */
function GM_deleteValue(name) {

}

/**
 *  @param string name
 *  @param mixed default Default result to be returned
 */
function GM_getValue(name, default) {

}

function GM_listValues() {

}

/**
 *  @param string name
 *  @param string value
 */
function GM_setValues(name, value) {

}

/**
 *  @param string resource Resource name
 */
function GM_getResourceText(resource) {

}

/**
 *  @param string resource Resource name
 */
function GM_getResourceURL(resource) {

}

/**
 *  @param string css String of CSS
 */
function GM_addStyle(css) {

}

/**
 *  @param boolean binary
 *  @param string data
 *  @param object headers
 *  @param string method
 *  @param function onAbort
 *  @param function onError
 *  @param function onLoad
 *  @param function onProgress
 *  @param function onReadyStateChange
 *  @param string overideMimeType
 *  @param string password
 *  @param boolean synchronous
 *  @param object upload
 *  @param string url
 *  @param string user
 */
function GM_xmlhttpRequest(binary,data,headers,method,onAbort,onError,onLoad,onProgress,onReadyStateChange,overideMimeType,password,synchronous,upload,url,user) {

}

/**
 *  @param string message
 */
function GM_log(message) {

}

/**
 *  @param string url
 */
function GM_openInTab(url) {

}

/**
 *  @param string caption
 *  @param function commandFunc
 *  @param string accessKey
 */
function GMregisterMenuCommand(caption,commandFunc,accessKey) {

}
<commit_msg>Renamed conflictive variable name<commit_after>/**
 *  KitScript - A User Script Safari Extension
 *
 *  Greasemonkey.js - Javascript file containing Greasemonkey classes
 *  (by Prototype.js) used globally in the extension & implementing core
 *  Greasemonkey API.
 *
 *  @author Seraf Dos Santos
 *  @copyright 2011-2012 Seraf Dos Santos - All rights reserved.
 *  @license MIT License
 *  @version 0.1
 */

/**
 *  KSGMUS (KitScript Greasemonkey User Script Class)
 */
var KSGMUS = Class.create({

    initialize: function (script) {

        this._script = script;
    },
    hasValidHeader: function () {

        var _isValid = /\/\/[ ]+==UserScript==\n.*\/\/[ ]+==\/UserScript==/g.test(this._script);

        return _isValid;
    },
    getIncludes: function () {

        var _includes = [];

        var matches = /\/\/[ ]+\@include (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _includes.push(matches[i]);
        }

        return _includes;
    },
    getExcludes: function () {

        var _excludes = [];

        var matches = /\/\/[ ]+\@exclude (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _excludes.push(matches[i]);
        }

        return _excludes;
    },
    getDescription: function () {

        var matches = /\/\/[ ]+\@description (.*)/g.exec(this._script);

        return matches[1];
    },
    getIcon: function () {

        var matches = /\/\/[ ]+\@icon (.*)/g.exec(this._script);

        return matches[1];
    },
    getMatches: function () {

        var _matches = [];

        var matches = /\/\/[ ]+\@match (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _matches.push(matches[i]);
        }

        return _matches;
    },
    getName: function () {

        var matches = /\/\/[ ]+\@name (.*)/g.exec(this._script);

        return matches[1];
    },
    getNamespace: function () {

        var matches = /\/\/[ ]+\@namespace (.*)/g.exec(this._script);

        return matches[1];
    },
    getRequires: function () {

        var _requires = [];

        var matches = /\/\/[ ]+\@match (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _requires.push(matches[i]);
        }

        return _requires;
    },
    getResources: function () {

        var _resources = [];

        var matches = /\/\/[ ]+\@resource (.*) (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _resources.push(new Array(matches[i], matches[i+1]));
        }

        return _resources;
    },
    getRunAt: function () {

        var matches = /\/\/[ ]+\@run-at (.*)/g.exec(this._script);

        return matches[1];
    },
    hasUnwrap: function () {

        var _hasUnwrap = /\/\/[ ]+\@unwrap (.*)/g.test(this._script);

        return _hasUnwrap;
    },
    getVersion: function () {

        var matches = /\/\/[ ]+\@version (.*)/g.exec(this._script);

        return matches[1];
    }
});

//
// Greasemonkey
//

/**
 *  @param string name
 */
function GM_deleteValue(name) {

}

/**
 *  @param string name
 *  @param mixed defaultVal Default result to be returned
 */
function GM_getValue(name, defaultVal) {

}

function GM_listValues() {

}

/**
 *  @param string name
 *  @param string value
 */
function GM_setValues(name, value) {

}

/**
 *  @param string resource Resource name
 */
function GM_getResourceText(resource) {

}

/**
 *  @param string resource Resource name
 */
function GM_getResourceURL(resource) {

}

/**
 *  @param string css String of CSS
 */
function GM_addStyle(css) {

}

/**
 *  @param boolean binary
 *  @param string data
 *  @param object headers
 *  @param string method
 *  @param function onAbort
 *  @param function onError
 *  @param function onLoad
 *  @param function onProgress
 *  @param function onReadyStateChange
 *  @param string overideMimeType
 *  @param string password
 *  @param boolean synchronous
 *  @param object upload
 *  @param string url
 *  @param string user
 */
function GM_xmlhttpRequest(binary,data,headers,method,onAbort,onError,onLoad,onProgress,onReadyStateChange,overideMimeType,password,synchronous,upload,url,user) {

}

/**
 *  @param string message
 */
function GM_log(message) {

}

/**
 *  @param string url
 */
function GM_openInTab(url) {

}

/**
 *  @param string caption
 *  @param function commandFunc
 *  @param string accessKey
 */
function GMregisterMenuCommand(caption,commandFunc,accessKey) {

}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule CheckBox
 * @flow
 * @format
 */
'use strict';

const NativeMethodsMixin = require('NativeMethodsMixin');
const PropTypes = require('prop-types');
const React = require('React');
const StyleSheet = require('StyleSheet');
const ViewPropTypes = require('ViewPropTypes');

const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');

type DefaultProps = {
  value: boolean,
  disabled: boolean,
};

/**
 * Renders a boolean input (Android only).
 *
 * This is a controlled component that requires an `onValueChange` callback that
 * updates the `value` prop in order for the component to reflect user actions.
 * If the `value` prop is not updated, the component will continue to render
 * the supplied `value` prop instead of the expected result of any user actions.
 *
 * @keyword checkbox
 * @keyword toggle
 */
let CheckBox = createReactClass({
  displayName: 'CheckBox',
  propTypes: {
    ...ViewPropTypes,
    /**
     * The value of the checkbox.  If true the checkbox will be turned on.
     * Default value is false.
     */
    value: PropTypes.bool,
    /**
     * If true the user won't be able to toggle the checkbox.
     * Default value is false.
     */
    disabled: PropTypes.bool,
    /**
     * Used in case the props change removes the component.
     */
    onChange: PropTypes.func,
    /**
     * Invoked with the new value when the value changes.
     */
    onValueChange: PropTypes.func,
    /**
     * Used to locate this view in end-to-end tests.
     */
    testID: PropTypes.string,
  },

  getDefaultProps: function(): DefaultProps {
    return {
      value: false,
      disabled: false,
    };
  },

  mixins: [NativeMethodsMixin],

  _rctCheckBox: {},
  _onChange: function(event: Object) {
    this._rctCheckBox.setNativeProps({value: this.props.value});
    // Change the props after the native props are set in case the props
    // change removes the component
    this.props.onChange && this.props.onChange(event);
    this.props.onValueChange &&
      this.props.onValueChange(event.nativeEvent.value);
  },

  render: function() {
    let props = {...this.props};
    props.onStartShouldSetResponder = () => true;
    props.onResponderTerminationRequest = () => false;
    props.enabled = !this.props.disabled;
    props.on = this.props.value;
    props.style = [styles.rctCheckBox, this.props.style];

    return (
      <RCTCheckBox
        {...props}
        ref={ref => {
          /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
           * comment suppresses an error when upgrading Flow's support for
           * React. To see the error delete this comment and run Flow. */
          this._rctCheckBox = ref;
        }}
        onChange={this._onChange}
      />
    );
  },
});

let styles = StyleSheet.create({
  rctCheckBox: {
    height: 32,
    width: 32,
  },
});

let RCTCheckBox = requireNativeComponent('AndroidCheckBox', CheckBox, {
  nativeOnly: {
    onChange: true,
    on: true,
    enabled: true,
  },
});

module.exports = CheckBox;
<commit_msg>Docs: Add example to CheckBox documentation<commit_after>/**
 * Copyright (c) 2017-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule CheckBox
 * @flow
 * @format
 */
'use strict';

const NativeMethodsMixin = require('NativeMethodsMixin');
const PropTypes = require('prop-types');
const React = require('React');
const StyleSheet = require('StyleSheet');
const ViewPropTypes = require('ViewPropTypes');

const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');

type DefaultProps = {
  value: boolean,
  disabled: boolean,
};

/**
 * Renders a boolean input (Android only).
 *
 * This is a controlled component that requires an `onValueChange` callback that
 * updates the `value` prop in order for the component to reflect user actions.
 * If the `value` prop is not updated, the component will continue to render
 * the supplied `value` prop instead of the expected result of any user actions.
 *
 * ```
 * import React from 'react';
 * import { AppRegistry, StyleSheet, Text, View, CheckBox } from 'react-native';
 *
 * export default class App extends React.Component {
 *   constructor(props) {
 *     super(props);
 *     this.state = {
 *       checked: false
 *     }
 *   }
 *
 *   toggle() {
 *     this.setState(({checked}) => {
 *       return {
 *         checked: !checked
 *       };
 *     });
 *   }
 *
 *   render() {
 *     const {checked} = this.state;
 *     return (
 *       <View style={styles.container}>
 *         <Text>Checked</Text>
 *         <CheckBox value={checked} onChange={this.toggle.bind(this)} />
 *       </View>
 *     );
 *   }
 * }
 *
 * const styles = StyleSheet.create({
 *   container: {
 *     flex: 1,
 *     flexDirection: 'row',
 *     alignItems: 'center',
 *     justifyContent: 'center',
 *   },
 * });
 *
 * // skip this line if using Create React Native App
 * AppRegistry.registerComponent('App', () => App);
 * ```
 *
 * @keyword checkbox
 * @keyword toggle
 */
let CheckBox = createReactClass({
  displayName: 'CheckBox',
  propTypes: {
    ...ViewPropTypes,
    /**
     * The value of the checkbox.  If true the checkbox will be turned on.
     * Default value is false.
     */
    value: PropTypes.bool,
    /**
     * If true the user won't be able to toggle the checkbox.
     * Default value is false.
     */
    disabled: PropTypes.bool,
    /**
     * Used in case the props change removes the component.
     */
    onChange: PropTypes.func,
    /**
     * Invoked with the new value when the value changes.
     */
    onValueChange: PropTypes.func,
    /**
     * Used to locate this view in end-to-end tests.
     */
    testID: PropTypes.string,
  },

  getDefaultProps: function(): DefaultProps {
    return {
      value: false,
      disabled: false,
    };
  },

  mixins: [NativeMethodsMixin],

  _rctCheckBox: {},
  _onChange: function(event: Object) {
    this._rctCheckBox.setNativeProps({value: this.props.value});
    // Change the props after the native props are set in case the props
    // change removes the component
    this.props.onChange && this.props.onChange(event);
    this.props.onValueChange &&
      this.props.onValueChange(event.nativeEvent.value);
  },

  render: function() {
    let props = {...this.props};
    props.onStartShouldSetResponder = () => true;
    props.onResponderTerminationRequest = () => false;
    props.enabled = !this.props.disabled;
    props.on = this.props.value;
    props.style = [styles.rctCheckBox, this.props.style];

    return (
      <RCTCheckBox
        {...props}
        ref={ref => {
          /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
           * comment suppresses an error when upgrading Flow's support for
           * React. To see the error delete this comment and run Flow. */
          this._rctCheckBox = ref;
        }}
        onChange={this._onChange}
      />
    );
  },
});

let styles = StyleSheet.create({
  rctCheckBox: {
    height: 32,
    width: 32,
  },
});

let RCTCheckBox = requireNativeComponent('AndroidCheckBox', CheckBox, {
  nativeOnly: {
    onChange: true,
    on: true,
    enabled: true,
  },
});

module.exports = CheckBox;
<|endoftext|>


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

// Closures

var globalVar = "xyz";

(function outerFunc(outerArg) {
  var outerVar = 'a';

  (function innerFunc(innerArg) {
    var innerVar = 'b';

    console.log(
      "outerArg = " + outerArg + "\n" +
      "innerArg = " + innerArg + "\n" +
      "outerVar = " + outerVar + "\n" +
      "innerVar = " + innerVar + "\n" +
      "globalVar = " + globalVar);

  })(456);
})(123);

var cascade = function() {

  // Sorry charlie, the loop will complete before any timeout fires, you'll get all 5's
  for (var i = 0; i < 5; i++) {
    setTimeout(function() { console.log(i); }, i * 1000 );
  }

  // USE let to cause i to have "block scope" (ie it will NOT be shared with internal scope!)
  for (let i = 0; i < 5; i++) {
    setTimeout(function() { console.log(i); }, i * 1000 );
  }

  // Or explicitly use a closure
  for (var i = 0; i < 5; i++) {
    (function(x) {
      setTimeout(function() { console.log(x); }, x * 1000 );
    })(i);
  }
}
cascade()<commit_msg>auto-sync<commit_after>#!/usr/bin/env node

// Closures

var globalVar = "xyz";

(function outerFunc(outerArg) {
  var outerVar = 'a';

  (function innerFunc(innerArg) {
    var innerVar = 'b';

    console.log(
      "outerArg = " + outerArg + "\n" +
      "innerArg = " + innerArg + "\n" +
      "outerVar = " + outerVar + "\n" +
      "innerVar = " + innerVar + "\n" +
      "globalVar = " + globalVar);

  })(456);
})(123);

var cascade = function() {

  // Sorry charlie, the loop will complete before any timeout fires, you'll get all 5's
  // BUT, the timing of the output will be good :-)
  for (var i = 0; i < 5; i++) {
    setTimeout(function() { console.log(i); }, i * 1000 );
  }

  // USE let to cause i to have "block scope" (ie it will NOT be shared with internal scope!)
  for (let i = 0; i < 5; i++) {
    setTimeout(function() { console.log(i); }, i * 1000 );
  }

  // Or explicitly use a closure
  for (var i = 0; i < 5; i++) {
    (function(x) {
      setTimeout(function() { console.log(x); }, x * 1000 );
    })(i);
  }
}
cascade()<|endoftext|>


<commit_before>function main(){
	 /**
     * Examples for using the parser:
     * var parser = new Parser("storagefacility.xml");
     * var parser = new Parser("sourcefacility.xml");
	 * var parser = new Parser("recipereactor.xml");
     * var parser = new Parser("file:///home/scopatz/cyclus/src/Models/Facility/StorageFacility/StorageFacility.rng");
     */
    var parser = new Parser(
        "file:///C:/Users/Kevin/Documents/GitHub/core/src/Models/Facility/SourceFacility/SourceFacility.rng");

  var parsed_obj = parser.parse_obj();
   //parser.printObject(parsed_obj, 0);
}

function mainGather(){
  /**
     * Examples for using mainGather
     * gatherSchemas('/home/scopatz/cyclus')
     * gatherSchemas('../../cyclus')
     * gatherSchemas('http://raw.github.com/cyclus/core/master/src/Models/Facility/StorageFacility/StorageFacility.rng');
     */
    gatherSchemas('file:///C:/Users/Kevin/Documents/GitHub/core');

}

function cycicXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        var xhttp = new XMLHttpRequest();
    }

    /** IE 5/6 */
    else {
        var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xhttp;
}
/******************************************************************************
 *                             Parser Class                                   *
 ******************************************************************************/

function Parser(word){
	this.currentIndex = new Array();
	this.jsObjName = new Array();
	this.elementTrace = new Array();
	this.file = word;
}

Parser.prototype.speak = function() {
	document.write(this.word);
}

/** Take XML and convert to JS object to be printed out. */
Parser.prototype.parse_obj = function() {
	if (this.file.URL == '') {
        var x = this.file.childNodes[0].childNodes;
    }
    else{
        var xhttp = cycicXMLHttpRequest()
        xhttp.open("GET", this.file, false);
        xhttp.send();
        xmlDoc=xhttp.responseXML;

        var x = xmlDoc.childNodes[0].childNodes;
    }

	/**
     * First, start looking for the main parent name by searching for the
     * 'define' tag
     */
	for(n=0; n<x.length; n++){
    /** If found, start printing out the children */
		if (x[n].nodeName === 'define'){
			var elements = x[n].childNodes[1].childNodes;
			this.jsObjName[x[n].childNodes[1].getAttribute('name')] = {};
            this.jsObjName[x[n].childNodes[1].getAttribute('name')] = this.parseObject(elements);
		}
	}
	return this.jsObjName;
}

Parser.prototype.parseObject = function(a){
	var spaces = new Array();
	result = {};
	for (i=0; i<a.length; i++){
		/** Extract only the element, not the text objects. */
		if(a[i].nodeName != '#text'){
			if(a[i].nodeName != '#comment'){
				var currentElement = a[i];

				/** If the object has a 'name' attribute, print it. */
				if(currentElement.getAttribute('name')){
					this.currentIndex.push(i);

					result[currentElement.getAttribute('name')] = {};
					this.elementTrace.push(result);
					tempList = this.parseObject(currentElement.childNodes);
					result = this.elementTrace.pop(result);
					result[currentElement.getAttribute('name')] = tempList;

					i = this.currentIndex.pop(i);
				}

				/** If the object has a 'type' attribute, print it. */
				else if(currentElement.getAttribute('type')){
					this.currentIndex.push(i);

					result[currentElement.getAttribute('type')] = {};
					this.elementTrace.push(result);
					tempList = this.parseObject(currentElement.childNodes);
					result = this.elementTrace.pop(result);
					result[currentElement.getAttribute('type')] = tempList;

					i = this.currentIndex.pop(i);
				}
				else if(currentElement.getAttribute('name') === null){
					if(currentElement.getAttribute('type') === null){

						this.currentIndex.push(i);

						result[currentElement.nodeName] = {};
						this.elementTrace.push(result);
						tempList = this.parseObject(currentElement.childNodes);
						result = this.elementTrace.pop(result);
						result[currentElement.nodeName] = tempList;

						i = this.currentIndex.pop(i);
					}
				}
			}
		}
	}
	return result;
}

/** Function used to recursively print the JS object. */
Parser.prototype.printObject = function(parsedObject, spaces) {
    var count = 0;

    /** Loop through each element in the object. */
    for (var key in parsedObject) {

        /** Keep track of the current index. */
        count++;

        /**
         * If the element has more than one child, print out the parent,
         * the children and its children.
         */
        if(this.getChildrenNum(parsedObject[key]) > 1){
            document.write("[\"" + key + "\",
");
            this.inputSpaces(spaces + 1);
            document.write("[
");
            this.inputSpaces(spaces + 2);
            this.printObject(parsedObject[key], spaces + 2);
            this.inputSpaces(spaces + 1);
            document.write("]
");
            this.inputSpaces(spaces);
            document.write("]
");
        }

        /**
         * If the element has exactly one child, print out the parent and its
         * single child.
         */
        else if (this.getChildrenNum(parsedObject[key]) == 1){
            document.write("[\"" + key + "\", ");
            length = this.getLength(parsedObject);
            tempKey = this.getKey(parsedObject[key]);

            /**
             * If the parent's child has no children, just print out the child with
             * closing brackets.
             */
            if (this.getChildrenNum(parsedObject[key][tempKey]) == 0){
                document.write("\"" + this.getKey(parsedObject[key]) + "\"");
                // Check if we are at the last element
                if(count == length){
                    document.write("]
");
                }
                else{
                    document.write("],
");
                    this.inputSpaces(spaces);
                }
            }

            /**
             * If the parent's child has children, print out everything and print the
             * children's children.
             */
            else {
                document.write("
");
                this.inputSpaces(spaces +1);
                tempKey = this.getKey(parsedObject[key]);

                if (this.getChildrenNum(parsedObject[key][tempKey]) ==1){
                    document.write("[");
                    this.printObject(parsedObject[key], spaces + 1);
                    this.inputSpaces(spaces);
                    document.write("]]
");
                }
                else{
                    this.printObject(parsedObject[key], spaces + 1);
                    this.inputSpaces(spaces);
                    document.write("]
");
                }
            }
        }

        /** If the parent has no child, it is a ref, so just print out the parent. */
        else if (this.getChildrenNum(parsedObject[key]) == 0){
            length = this.getLength(parsedObject);

            /**If it is the last element, print just a newline. */
            if (count == length) {
                document.write("\"" + key + "\"
");
            }
            else {
                document.write("\"" + key + "\",
");
                this.inputSpaces(spaces);
            }
        }
    }
}

/** Helper function used to get the length of the elements within a parent. */
Parser.prototype.getLength = function(object) {
	var length = 0;
	for (var key in object){
		length++;
	}
	return length;
}

/**
 * Helper function used to get the key value in an object.
 * Only used when we know that the parent has just one child.
 */
Parser.prototype.getKey = function(object) {
	var att = "";
	for (var key in object) {
		att = key;
	}
	return att;
}

/** Helper function used to determine the number of children in a node. */
Parser.prototype.getChildrenNum = function(node) {
	var count = 0;
	for (var key in node){
		if (key) {
			count++;
		}
	}
	return count;
}

/** Helper function used to print out 'num' amount of tabs for formatting purposes. */
Parser.prototype.inputSpaces = function(num) {
	for(k=0; k < num; k ++){
		document.write('&nbsp&nbsp&nbsp&nbsp');
	}
}

function gatherSchemas(cyclusPath){

  /** Default arguments. */
  cyclusPath = typeof cyclusPath !== 'undefined' ? cyclusPath : ''
  if (cyclusPath == ''){
	console.error("cyclusPath is empty")
  }

  /** Local vars. */
  var i = 0
  var parser = null
  var schemas = {}
  var rngRelPath = ""
  var rngFullPath = ""
  var reFac = /eFacility/

  /** Get the list of all rng files and parse them. */
  var xhttp = cycicXMLHttpRequest();
  xhttp.open("GET", "rngdump.json", false)
  xhttp.send()
  var rngPaths = JSON.parse(xhttp.responseText)
  //document.write(typeof(rngPaths) + "
")
  //document.write(Object.prototype.toString.call(rngPaths) + "
")
  for (i in rngPaths) {
	rngRelPath = rngPaths[i]

        /** Test to see if server request works. */
        rngRelPath =
            "\"https://raw.github.com/cyclus/core/master/src/Models/Facility/StorageFacility/StorageFacility.rng\""
        if (rngRelPath.slice(0,4) == '\"htt'){
            $(document).ready(function() {
                $.ajax({
                    crossDomain: true,
                    type: 'GET',
                    url: 'http://query.yahooapis.com/v1/public/yql?q=select * from xml where url=' + rngRelPath,
                    dataType: 'jsonp',
                    success: function(response){
                        if(response.results[0] != undefined){
                            var text = response.results[0];
                            if (window.ActiveXObject){
                                var doc=new ActiveXObject('Microsoft.XMLDOM');
                                doc.async='false';
                                doc.loadXML(text);
                            } else {
                            var parser=new DOMParser();
                            var doc=parser.parseFromString(text,'text/xml');
                            }

                            var parser = new Parser(doc);
                            var parsedObj = parser.parse_obj();
                            schemas[rngRelPath] = parse_obj();
                            //parser.printObject(parsedObj, 0);
                        }
                        else{
                            alert('Response undefined; incorrect url');
                        }
                    }
                })
            });
            break;
        }
        else{
            rngFullPath = cyclusPath + '/' + rngRelPath;
            parser = new Parser(rngFullPath);
            schemas[rngRelPath] = parser.parse_obj();

            /**
             * if (rngRelPath.match(reFac) !== null) {
             * schemas[rngRelPath] = new Parser(rngFullPath)
             * }
             */
        }
  }

  for (s in schemas) {
	document.write(s + ":  " + "
")
	//var parser = new Parser('blah')
	//parser.printObject(schemas[s],0)
  }
  //document.write(schemas);
  return schemas;
}

//main();
mainGather();

/**
 * MENTAL NOTES TO SELF
 */

/**
xmlDoc.childNodes[0].nodeName -- 'grammer'
xmlDoc.childNodes[0].childNodes[1].nodeName -- 'define'
xmlDoc.childNodes[0].childNodes[1].childNodes[1] --element RecipeReactor
xmlDoc.childNodes[0].childNodes[1].childNodes[1].childNodes[1].nodeName --oneOrMore

for(i=0; i<elements.length; i++){
	document.write(elements[1].childNodes[i]);
}

//print tag name and value of the name attribute. change 'name' to type to get the data type of the object
document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].getAttribute('name'));
document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].nodeName);

//prints inrecipt.. why
document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].nextSibling.nextSibling.getAttribute('name'));
**/

<commit_msg>No idea how to fix this excpet by adding a global var.<commit_after>function main(){
	 /**
     * Examples for using the parser:
     * var parser = new Parser("storagefacility.xml");
     * var parser = new Parser("sourcefacility.xml");
	 * var parser = new Parser("recipereactor.xml");
     * var parser = new Parser("file:///home/scopatz/cyclus/src/Models/Facility/StorageFacility/StorageFacility.rng");
     */
    var parser = new Parser(
        "file:///C:/Users/Kevin/Documents/GitHub/core/src/Models/Facility/SourceFacility/SourceFacility.rng");

  var parsed_obj = parser.parse_obj();
   //parser.printObject(parsed_obj, 0);
}

function mainGather(){
  /**
     * Examples for using mainGather
     * gatherSchemas('/home/scopatz/cyclus')
     * gatherSchemas('../../cyclus')
     * gatherSchemas('http://raw.github.com/cyclus/core/master/src/Models/Facility/StorageFacility/StorageFacility.rng');
     */
    gatherSchemas('file:///C:/Users/Kevin/Documents/GitHub/core');

}

function cycicXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        var xhttp = new XMLHttpRequest();
    }

    /** IE 5/6 */
    else {
        var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xhttp;
}
/******************************************************************************
 *                             Parser Class                                   *
 ******************************************************************************/

function Parser(word){
	this.currentIndex = new Array();
	this.jsObjName = new Array();
	this.elementTrace = new Array();
	this.file = word;
}

Parser.prototype.speak = function() {
	document.write(this.word);
}

/** Take XML and convert to JS object to be printed out. */
Parser.prototype.parse_obj = function() {
	if (this.file.URL == '') {
        var x = this.file.childNodes[0].childNodes;
    }
    else{
        var xhttp = cycicXMLHttpRequest()
        xhttp.open("GET", this.file, false);
        xhttp.send();
        xmlDoc=xhttp.responseXML;

        var x = xmlDoc.childNodes[0].childNodes;
    }

	/**
     * First, start looking for the main parent name by searching for the
     * 'define' tag
     */
	for(n=0; n<x.length; n++){
    /** If found, start printing out the children */
		if (x[n].nodeName === 'define'){
			var elements = x[n].childNodes[1].childNodes;
			this.jsObjName[x[n].childNodes[1].getAttribute('name')] = {};
            this.jsObjName[x[n].childNodes[1].getAttribute('name')] = this.parseObject(elements);
		}
	}
	return this.jsObjName;
}

Parser.prototype.parseObject = function(a){
	var spaces = new Array();
	result = {};
	for (i=0; i<a.length; i++){
		/** Extract only the element, not the text objects. */
		if(a[i].nodeName != '#text'){
			if(a[i].nodeName != '#comment'){
				var currentElement = a[i];

				/** If the object has a 'name' attribute, print it. */
				if(currentElement.getAttribute('name')){
					this.currentIndex.push(i);

					result[currentElement.getAttribute('name')] = {};
					this.elementTrace.push(result);
					tempList = this.parseObject(currentElement.childNodes);
					result = this.elementTrace.pop(result);
					result[currentElement.getAttribute('name')] = tempList;

					i = this.currentIndex.pop(i);
				}

				/** If the object has a 'type' attribute, print it. */
				else if(currentElement.getAttribute('type')){
					this.currentIndex.push(i);

					result[currentElement.getAttribute('type')] = {};
					this.elementTrace.push(result);
					tempList = this.parseObject(currentElement.childNodes);
					result = this.elementTrace.pop(result);
					result[currentElement.getAttribute('type')] = tempList;

					i = this.currentIndex.pop(i);
				}
				else if(currentElement.getAttribute('name') === null){
					if(currentElement.getAttribute('type') === null){

						this.currentIndex.push(i);

						result[currentElement.nodeName] = {};
						this.elementTrace.push(result);
						tempList = this.parseObject(currentElement.childNodes);
						result = this.elementTrace.pop(result);
						result[currentElement.nodeName] = tempList;

						i = this.currentIndex.pop(i);
					}
				}
			}
		}
	}
	return result;
}

/** Function used to recursively print the JS object. */
Parser.prototype.printObject = function(parsedObject, spaces) {
    var count = 0;

    /** Loop through each element in the object. */
    for (var key in parsedObject) {

        /** Keep track of the current index. */
        count++;

        /**
         * If the element has more than one child, print out the parent,
         * the children and its children.
         */
        if(this.getChildrenNum(parsedObject[key]) > 1){
            document.write("[\"" + key + "\",
");
            this.inputSpaces(spaces + 1);
            document.write("[
");
            this.inputSpaces(spaces + 2);
            this.printObject(parsedObject[key], spaces + 2);
            this.inputSpaces(spaces + 1);
            document.write("]
");
            this.inputSpaces(spaces);
            document.write("]
");
        }

        /**
         * If the element has exactly one child, print out the parent and its
         * single child.
         */
        else if (this.getChildrenNum(parsedObject[key]) == 1){
            document.write("[\"" + key + "\", ");
            length = this.getLength(parsedObject);
            tempKey = this.getKey(parsedObject[key]);

            /**
             * If the parent's child has no children, just print out the child with
             * closing brackets.
             */
            if (this.getChildrenNum(parsedObject[key][tempKey]) == 0){
                document.write("\"" + this.getKey(parsedObject[key]) + "\"");
                // Check if we are at the last element
                if(count == length){
                    document.write("]
");
                }
                else{
                    document.write("],
");
                    this.inputSpaces(spaces);
                }
            }

            /**
             * If the parent's child has children, print out everything and print the
             * children's children.
             */
            else {
                document.write("
");
                this.inputSpaces(spaces +1);
                tempKey = this.getKey(parsedObject[key]);

                if (this.getChildrenNum(parsedObject[key][tempKey]) ==1){
                    document.write("[");
                    this.printObject(parsedObject[key], spaces + 1);
                    this.inputSpaces(spaces);
                    document.write("]]
");
                }
                else{
                    this.printObject(parsedObject[key], spaces + 1);
                    this.inputSpaces(spaces);
                    document.write("]
");
                }
            }
        }

        /** If the parent has no child, it is a ref, so just print out the parent. */
        else if (this.getChildrenNum(parsedObject[key]) == 0){
            length = this.getLength(parsedObject);

            /**If it is the last element, print just a newline. */
            if (count == length) {
                document.write("\"" + key + "\"
");
            }
            else {
                document.write("\"" + key + "\",
");
                this.inputSpaces(spaces);
            }
        }
    }
}

/** Helper function used to get the length of the elements within a parent. */
Parser.prototype.getLength = function(object) {
	var length = 0;
	for (var key in object){
		length++;
	}
	return length;
}

/**
 * Helper function used to get the key value in an object.
 * Only used when we know that the parent has just one child.
 */
Parser.prototype.getKey = function(object) {
	var att = "";
	for (var key in object) {
		att = key;
	}
	return att;
}

/** Helper function used to determine the number of children in a node. */
Parser.prototype.getChildrenNum = function(node) {
	var count = 0;
	for (var key in node){
		if (key) {
			count++;
		}
	}
	return count;
}

/** Helper function used to print out 'num' amount of tabs for formatting purposes. */
Parser.prototype.inputSpaces = function(num) {
	for(k=0; k < num; k ++){
		document.write('&nbsp&nbsp&nbsp&nbsp');
	}
}

var schemas = {}

function gatherSchemas(cyclusPath){

  /** Default arguments. */
  cyclusPath = typeof cyclusPath !== 'undefined' ? cyclusPath : ''
  if (cyclusPath == ''){
	console.error("cyclusPath is empty")
  }

  /** Local vars. */
  var i = 0
  var parser = null
  var schemas = {}
  var rngRelPath = ""
  var rngFullPath = ""
  var reFac = /eFacility/

  /** Get the list of all rng files and parse them. */
  var xhttp = cycicXMLHttpRequest();
  xhttp.open("GET", "rngdump.json", false)
  xhttp.send()
  var rngPaths = JSON.parse(xhttp.responseText)
  //document.write(typeof(rngPaths) + "
")
  //document.write(Object.prototype.toString.call(rngPaths) + "
")
  for (i in rngPaths) {
	rngRelPath = rngPaths[i]

        /** Test to see if server request works. */
        rngRelPath =
            "\"https://raw.github.com/cyclus/cyclus/master/src/Models/Facility/StorageFacility/StorageFacility.rng\""
        if (rngRelPath.slice(0,4) == '\"htt'){
            $(document).ready(function() {
                $.ajax({
                    crossDomain: true,
                    type: 'GET',
                    url: 'http://query.yahooapis.com/v1/public/yql?q=select * from xml where url=' + rngRelPath,
                    dataType: 'jsonp',
                    success: function(response){
                        if(response.results[0] != undefined){
                            var text = response.results[0];
                            if (window.ActiveXObject){
                                var doc=new ActiveXObject('Microsoft.XMLDOM');
                                doc.async='false';
                                doc.loadXML(text);
                            } else {
                            var parser=new DOMParser();
                            var doc=parser.parseFromString(text,'text/xml');
                            }

                            var parser = new Parser(doc);
                            var parsedObj = parser.parse_obj();
                            schemas[rngRelPath] = parsedObj;
                            //parser.printObject(parsedObj, 0);
                        }
                        else{
                            alert('Response undefined; incorrect url');
                        }
                    }
                })
            });
            break;
        }
        else{
            rngFullPath = cyclusPath + '/' + rngRelPath;
            parser = new Parser(rngFullPath);
            schemas[rngRelPath] = parser.parse_obj();

            /**
             * if (rngRelPath.match(reFac) !== null) {
             * schemas[rngRelPath] = new Parser(rngFullPath)
             * }
             */
        }
  }

  for (s in schemas) {
	document.write(s + ":  " + "
")
	//var parser = new Parser('blah')
	//parser.printObject(schemas[s],0)
  }
  //document.write(schemas);
  return schemas;
}

//main();
mainGather();

/**
 * MENTAL NOTES TO SELF
 */

/**
xmlDoc.childNodes[0].nodeName -- 'grammer'
xmlDoc.childNodes[0].childNodes[1].nodeName -- 'define'
xmlDoc.childNodes[0].childNodes[1].childNodes[1] --element RecipeReactor
xmlDoc.childNodes[0].childNodes[1].childNodes[1].childNodes[1].nodeName --oneOrMore

for(i=0; i<elements.length; i++){
	document.write(elements[1].childNodes[i]);
}

//print tag name and value of the name attribute. change 'name' to type to get the data type of the object
document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].getAttribute('name'));
document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].nodeName);

//prints inrecipt.. why
document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].nextSibling.nextSibling.getAttribute('name'));
**/

<|endoftext|>


<commit_before>"use strict";

var actions     = require("./actions").actions;
var character   = require("./character").character;
var destringify = require("./destringify_http").destringify;
var functions   = require("./functions");
var options     = require("./options");
var outcomes    = require("./outcomes");
var persons     = require("./persons").persons;
var places      = require("./places").places;

var express     = require("express");
var http        = require("http");
var port        = 3000;
var app;
var server;

app = express();

app.get("/request_initial_world.json", respond_with_initial_world);
app.get("/request_outcome_of_action.json", respond_with_outcome);
app.use(express.static(__dirname));

server = http.createServer(app);
server.listen(port);

function get_destination(game_state) {
    var links = game_state.places[game_state.character.place].links;
    var destination = links[functions.random_int(links.length)];
    return destination;
}

function respond_with_initial_world(req, res) {
    var game_state = {
        "action":      null,
        "character":   character,
        "destination": null,
        "for_sell":    null,
        "marriage":    false,
        "message":     "You are in a tavern. The local assassins hate you.",
        "options":     options.starting_options,
        "outcome":     null,
        "persons":     persons,
        "places":      places,
        "score":       0,
        "topic":       null,
    };
    res.json(game_state);
}

function respond_with_outcome(req, res) {
    if (validate_input(req.query) === true) {
        var game_state     = req.query;
        game_state         = destringify(game_state);
        var old_outcome    = game_state.outcome;
        var outcome        = outcomes.get_outcome(game_state);
        game_state.outcome = outcome;
        game_state         = outcomes.apply_outcome(outcome, game_state);
        game_state.options = options.get_options(game_state);
        set_destination(game_state, old_outcome);
        game_state.score   = parseInt(game_state.score) + 1;
        stop_tripping(game_state);
        res.json(game_state);
    } else {
        res.json({"message": "error"});
    }
}

function set_destination(game_state, old_outcome) {
    if (game_state.options.c === "GO_TO") {
        switch (old_outcome) {
            case "directions_to_manor":
                game_state.destination = "lord_bartholomew_manor";
                break;
            case "directions_to_town":
                game_state.destination = "streets";
                break;
            case "directions_to_woods":
                game_state.destination = "woods";
                break;
            default:
                game_state.destination = get_destination(game_state);
        }
    } else {
        game_state.destination = null;
    }
}

function stop_tripping(game_state) {
    if (game_state.character.is_tripping &&
        Math.floor(Math.random() * 4) === 0) {
        game_state.character.is_tripping = false;
    }
}

function validate_input(game_state) {
    var conditions = [
        typeof(game_state) === "object",

        typeof(game_state.character)        === "object",
        typeof(game_state.character.excuse) === "string",

        game_state.character.has_found_true_love === "false" ||
        game_state.character.has_found_true_love === "true",
        game_state.character.has_lost_leg        === "false" ||
        game_state.character.has_lost_leg        === "true",
        game_state.character.has_tail            === "false" ||
        game_state.character.has_tail            === "true",
        game_state.character.is_dead             === "false" ||
        game_state.character.is_dead             === "true",
        game_state.character.is_frog             === "false" ||
        game_state.character.is_frog             === "true",
        game_state.character.is_monstrosity      === "false" ||
        game_state.character.is_monstrosity      === "true",
        game_state.character.is_threatened       === "false" ||
        game_state.character.is_threatened       === "true",
        game_state.character.is_tripping         === "false" ||
        game_state.character.is_tripping         === "true",

        game_state.character.money === "none" ||
        game_state.character.money === "pittance" ||
        game_state.character.money === "small_fortune" ||
        game_state.character.money === "large_fortune",

        typeof(persons[game_state.character.person]) === "object" ||
        game_state.character.person === "",

        typeof(places[game_state.character.place]) === "object" ||
        game_state.character.place === "",

        !isNaN(parseInt(game_state.character.strength)),

        typeof(game_state.destination) === "string" &&
        (game_state.destination === "" ||
         typeof(places[game_state.destination]) === "object"),

        // TODO fix for_sell system and its validation
        typeof(game_state.for_sell)    === "string",

        typeof(game_state.message) === "string",

        typeof(game_state.options)             === "object" &&
        typeof(actions[game_state.options.a])  === "function" &&
        typeof(actions[game_state.options.b])  === "function" &&
        (typeof(actions[game_state.options.c]) === "function" ||
         game_state.options.c === "") &&
        (typeof(actions[game_state.options.d]) === "function" ||
         game_state.options.d === "") &&
        (typeof(actions[game_state.options.e]) === "function" ||
         game_state.options.e === "") &&

        typeof(game_state.outcome) === "string" &&
        (game_state.outcome === "" ||
         typeof(outcomes.outcomes[game_state.outcome]) === "function"),

        typeof(game_state.persons) === "object",
        typeof(game_state.places)  === "object",

        typeof(game_state.score) === "string" &&
        !isNaN(parseInt(game_state.score)),

        typeof(game_state.topic) === "string",
    ];

    for (var item in game_state.character.items) {
        conditions.push(!isNaN(parseInt(game_state.character.items[item])));
    }

    //return a boolean that says if all conditions in the list are true or not
    return conditions.every(function(condition) {
        return condition;
    });
}
<commit_msg>continued working on input validation and broke parts of it up into multiple functions<commit_after>"use strict";

var actions     = require("./actions").actions;
var character   = require("./character").character;
var destringify = require("./destringify_http").destringify;
var functions   = require("./functions");
var options     = require("./options");
var outcomes    = require("./outcomes");
var persons     = require("./persons").persons;
var places      = require("./places").places;

var express     = require("express");
var http        = require("http");
var port        = 3000;
var app;
var server;

app = express();

app.get("/request_initial_world.json", respond_with_initial_world);
app.get("/request_outcome_of_action.json", respond_with_outcome);
app.use(express.static(__dirname));

server = http.createServer(app);
server.listen(port);

function get_destination(game_state) {
    var links = game_state.places[game_state.character.place].links;
    var destination = links[functions.random_int(links.length)];
    return destination;
}

function respond_with_initial_world(req, res) {
    var game_state = {
        "action":      null,
        "character":   character,
        "destination": null,
        "for_sell":    null,
        "marriage":    false,
        "message":     "You are in a tavern. The local assassins hate you.",
        "options":     options.starting_options,
        "outcome":     null,
        "persons":     persons,
        "places":      places,
        "score":       0,
        "topic":       null,
    };
    res.json(game_state);
}

function respond_with_outcome(req, res) {
    if (validate(req.query) === true) {
        var game_state     = req.query;
        game_state         = destringify(game_state);
        var old_outcome    = game_state.outcome;
        var outcome        = outcomes.get_outcome(game_state);
        game_state.outcome = outcome;
        game_state         = outcomes.apply_outcome(outcome, game_state);
        game_state.options = options.get_options(game_state);
        set_destination(game_state, old_outcome);
        game_state.score   = parseInt(game_state.score) + 1;
        stop_tripping(game_state);
        res.json(game_state);
    } else {
        res.json({"message": "error"});
    }
}

function set_destination(game_state, old_outcome) {
    if (game_state.options.c === "GO_TO") {
        switch (old_outcome) {
            case "directions_to_manor":
                game_state.destination = "lord_bartholomew_manor";
                break;
            case "directions_to_town":
                game_state.destination = "streets";
                break;
            case "directions_to_woods":
                game_state.destination = "woods";
                break;
            default:
                game_state.destination = get_destination(game_state);
        }
    } else {
        game_state.destination = null;
    }
}

function stop_tripping(game_state) {
    if (game_state.character.is_tripping &&
        Math.floor(Math.random() * 4) === 0) {
        game_state.character.is_tripping = false;
    }
}

function validate(game_state, conditions) {
    var conditions = [
        typeof(game_state) === "object",

        typeof(game_state.destination) === "string" &&
        (game_state.destination === "" ||
         typeof(places[game_state.destination]) === "object"),

        // TODO fix for_sell system and its validation
        typeof(game_state.for_sell)    === "string",

        typeof(game_state.message) === "string",

        typeof(game_state.outcome) === "string" &&
        (game_state.outcome === "" ||
         typeof(outcomes.outcomes[game_state.outcome]) === "function"),

        typeof(game_state.persons) === "object",
        typeof(game_state.places)  === "object",

        typeof(game_state.score) === "string" &&
        !isNaN(parseInt(game_state.score)),

        typeof(game_state.topic) === "string",
    ];

    if (validate_character(game_state) === false ||
        validate_options(game_state) === false) {
        return false;
    }

    //return a boolean that says if all conditions in the list are true or not
    return conditions.every(function(condition) {
        return condition;
    });
}

function validate_character(game_state) {

    var character_keys = Object.keys(character);
    var input_character_keys = Object.keys(game_state.character);
    if (character_keys.length === input_character_keys.length) {
        for (var i in character_keys) {
            if (character_keys[i] !== input_character_keys[i]) {
                return false;
            }
        }
    } else {
        return false;
    }

    var conditions = [
        typeof(game_state.character)        === "object",
        typeof(game_state.character.excuse) === "string",

        game_state.character.has_found_true_love === "false" ||
        game_state.character.has_found_true_love === "true",
        game_state.character.has_lost_leg        === "false" ||
        game_state.character.has_lost_leg        === "true",
        game_state.character.has_tail            === "false" ||
        game_state.character.has_tail            === "true",
        game_state.character.is_dead             === "false" ||
        game_state.character.is_dead             === "true",
        game_state.character.is_frog             === "false" ||
        game_state.character.is_frog             === "true",
        game_state.character.is_monstrosity      === "false" ||
        game_state.character.is_monstrosity      === "true",
        game_state.character.is_threatened       === "false" ||
        game_state.character.is_threatened       === "true",
        game_state.character.is_tripping         === "false" ||
        game_state.character.is_tripping         === "true",

        game_state.character.money === "none" ||
        game_state.character.money === "pittance" ||
        game_state.character.money === "small_fortune" ||
        game_state.character.money === "large_fortune",

        typeof(persons[game_state.character.person]) === "object" ||
        game_state.character.person === "",

        typeof(places[game_state.character.place]) === "object" ||
        game_state.character.place === "",

        !isNaN(parseInt(game_state.character.strength)),
    ];

    for (var item in game_state.character.items) {
        conditions.push(!isNaN(parseInt(game_state.character.items[item])));
    }

    return conditions.every(function(condition) {
        return condition;
    });

}

function validate_options(game_state) {
    return typeof(game_state.options)             === "object" &&
           typeof(actions[game_state.options.a])  === "function" &&
           typeof(actions[game_state.options.b])  === "function" &&
           (typeof(actions[game_state.options.c]) === "function" ||
            game_state.options.c === "") &&
           (typeof(actions[game_state.options.d]) === "function" ||
            game_state.options.d === "") &&
           (typeof(actions[game_state.options.e]) === "function" ||
            game_state.options.e === "");
}
<|endoftext|>


<commit_before>//v0.6
$(document).ready(function() {
	setTimeout(function() {
    $("#imgur img.lazy").lazyload({
        effect : "fadeIn",
        skip_invisible : true
    });

    $("#hizliresim img.lazy").lazyload({
        effect : "fadeIn",
        skip_invisible : true
    });
     $("#lowres img.lazy").lazyload({
        effect : "fadeIn",
        skip_invisible : true
    });
     $("#vanillaskins img.lazy").lazyload({
        effect : "fadeIn",
        skip_invisible : true
    });

    $("img.lazy").on("click", function(e) {
        e.preventDefault();
		var url = $(this).attr("name");

        //var url = $(this).attr("src");
        $("#skin-url").val(url).select();
        try {
            //document.execCommand("copy");
        } catch (e) {}
    });

    $("#skin-url").on("click", function(e) {
        $(this).select();
        try {
            //document.execCommand("copy");
        } catch (e) {}
    });

	$("#nav a").on("click", function() {
        var _this = $(this);
        if (_this.hasClass("link")) {
            return;
        }
        $("#nav a").removeClass("active");
        _this.addClass("active");
        var id = _this.attr("href");
        $(".skins-wrapper").hide();
        $(id).show();
        $(window).scrollTop(0).trigger("scroll");
        return false;
    });
    $("#UseEffect").on("click", function(e) {
		if ($("#nick").val().includes('℄') || window.proLicenceUID){
			try {
			//    window.parent.postMessage("CustomSkins&?skin="+$("#skin-url").val(), "*");
			toastr.info("[SERVER]: Special Effect " + $("#skin-url").val() + " activated");
			for (var i = 0; i < $(".skins-wrapper").length; i++){
				if ($(".skins-wrapper")[i].style.display != "none"){
					for (var j = 0; j < document.getElementsByClassName("skins-wrapper")[i].children.length; j++)
						if (document.getElementsByClassName("skins-wrapper")[i].children[j].children[0].name ==$("#skin-url").val()){
							if (document.getElementsByClassName("skins-wrapper")[2].children[0]) document.getElementsByClassName("skins-wrapper")[0].append(document.getElementsByClassName("skins-wrapper")[2].children[0])
							document.getElementsByClassName("skins-wrapper")[2].append(document.getElementsByClassName("skins-wrapper")[i].children[j])
						}
						else if (document.getElementsByClassName("skins-wrapper")[i].children[j].children[2].name ==$("#skin-url").val()){
							SpecialEffectPlayers[application.lastSentNick]=null
							window.isActualUsingSpecialEffectsSkin=null
							window.application.sendSocket3Info("spfc", null)
							toastr.info("[SERVER]: Special Effect " + $("#skin-url").val() + " de-activated");
						}
				}
			}
			application.lastSentNick = $("#nick").val()
			SpecialEffectPlayers[application.lastSentNick]=$("#skin-url").val()
			window.isActualUsingSpecialEffectsSkin=$("#skin-url").val()
			window.application.sendSocket3Info("spfc", $("#skin-url").val())

			} catch (e) {}
		}
		else{
			toastr.warning("[SERVER]: Not Premium account found. If you donated in the past, please refer it to Legend mod discord.
Thank you for using Legend mod!").css("width", "350px");
		}
    });
	setTimeout(function() {
		$("#nav a")[0].click();
	}, 100);
	}, 100);
});
<commit_msg>Update shopscript.js<commit_after>//v0.7
$(document).ready(function() {
	setTimeout(function() {
    $("#imgur img.lazy").lazyload({
        effect : "fadeIn",
        skip_invisible : true
    });

    $("#hizliresim img.lazy").lazyload({
        effect : "fadeIn",
        skip_invisible : true
    });
     $("#lowres img.lazy").lazyload({
        effect : "fadeIn",
        skip_invisible : true
    });
     $("#vanillaskins img.lazy").lazyload({
        effect : "fadeIn",
        skip_invisible : true
    });

    $("img.lazy").on("click", function(e) {
        e.preventDefault();
		var url = $(this).attr("name");

        //var url = $(this).attr("src");
        $("#skin-url").val(url).select();
        try {
            //document.execCommand("copy");
        } catch (e) {}
    });

    $("#skin-url").on("click", function(e) {
        $(this).select();
        try {
            //document.execCommand("copy");
        } catch (e) {}
    });

	$("#nav a").on("click", function() {
        var _this = $(this);
        if (_this.hasClass("link")) {
            return;
        }
        $("#nav a").removeClass("active");
        _this.addClass("active");
        var id = _this.attr("href");
        $(".skins-wrapper").hide();
        $(id).show();
        $(window).scrollTop(0).trigger("scroll");
        return false;
    });
    $("#UseEffect").on("click", function(e) {
		if ($("#nick").val().includes('℄') || window.proLicenceUID){
			try {
			//    window.parent.postMessage("CustomSkins&?skin="+$("#skin-url").val(), "*");
			toastr.info("[SERVER]: Special Effect " + $("#skin-url").val() + " activated");
			for (var i = 0; i < $(".skins-wrapper").length; i++){
				if ($(".skins-wrapper")[i].style.display != "none"){
					for (var j = 0; j < document.getElementsByClassName("skins-wrapper")[i].children.length; j++)
						if (document.getElementsByClassName("skins-wrapper")[i].children[j].children[0].name ==$("#skin-url").val()){
							if (document.getElementsByClassName("skins-wrapper")[2].children[0]){
								document.getElementsByClassName("skins-wrapper")[0].append(document.getElementsByClassName("skins-wrapper")[2].children[0])
							}
							document.getElementsByClassName("skins-wrapper")[2].append(document.getElementsByClassName("skins-wrapper")[i].children[j])
							application.lastSentNick = $("#nick").val()
							SpecialEffectPlayers[application.lastSentNick]=$("#skin-url").val()
							window.isActualUsingSpecialEffectsSkin=$("#skin-url").val()
							window.application.sendSocket3Info("spfc", $("#skin-url").val())
						}
						else if (document.getElementsByClassName("skins-wrapper")[i].children[j].children[2].name ==$("#skin-url").val()){
							SpecialEffectPlayers[application.lastSentNick]=null
							window.isActualUsingSpecialEffectsSkin=null
							window.application.sendSocket3Info("spfc", null)
							toastr.info("[SERVER]: Special Effect " + $("#skin-url").val() + " de-activated");
						}
				}
			}
			} catch (e) {}
		}
		else{
			toastr.warning("[SERVER]: Not Premium account found. If you donated in the past, please refer it to Legend mod discord.
Thank you for using Legend mod!").css("width", "350px");
		}
    });
	setTimeout(function() {
		$("#nav a")[0].click();
	}, 100);
	}, 50);
});
<|endoftext|>


<commit_before>/// <binding AfterBuild='nuget-pack' />
"use strict";

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

var solutionFolder = path.resolve(__dirname, '..');
var projectFolder = path.join(solutionFolder, 'MAB.SimpleMapper');
var distFolder = path.join(solutionFolder, 'dist');

if (!fs.existsSync(distFolder)) {
    fs.mkdirSync(distFolder);
}

gulp.task('nuget-pack', function (callback) {
    exec('nuget pack MAB.SimpleMapper.csproj -Symbols -OutputDirectory ' + distFolder + ' -Prop Configuration=Release', { cwd: projectFolder }, function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        callback(err);
    });
});
<commit_msg>Add clean task for package publishing<commit_after>/// <binding AfterBuild='nuget-pack' />
"use strict";

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

var solutionFolder = path.resolve(__dirname, '..');
var projectFolder = path.join(solutionFolder, 'MAB.SimpleMapper');
var distFolder = path.join(solutionFolder, 'dist');

if (!fs.existsSync(distFolder)) {
    fs.mkdirSync(distFolder);
}

gulp.task('nuget-clean', function (callback) {
    exec('del *.nupkg', { cwd: distFolder }, function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        callback(err);
    });
});

gulp.task('nuget-pack', ['nuget-clean'], function (callback) {
    exec('nuget pack MAB.SimpleMapper.csproj -Symbols -OutputDirectory ' + distFolder + ' -Prop Configuration=Release', { cwd: projectFolder }, function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        callback(err);
    });
});
<|endoftext|>


<commit_before>"use strict";

Module.register("MMM-PublicTransportBerlin", {
  // default values
  defaults: {
    name: "MMM-PublicTransportBerlin",  // The name of this module
    hidden: false,                      // Hide this module?
    stationId: "900000160003",          // The ID of the station
 //   directionStationId: 0,             // The stationId of the next station in which direction departures should be shown
    ignoredStations: [],                // Which stations should be ignored? (comma-separated list of station IDs)
    ignoredLines: [],                   // Which lines should be ignored? (comma-separated list of line names)
    excludedTransportationTypes: "",    // Which transportation types should not be shown on the mirror? (comma-separated list of types) possible values: bus,tram,suburban,subway,ferry
    marqueeLongDirections: true,        // Use Marquee effect for long station names?
    travelTimeToStation: 10,            // How long do you need to walk/bike to the next Station?
    interval: 120000,                   // How often should the table be updated in ms?
    departureMinutes: 30,               // For how many minutes should departures be shown?
    showColoredLineSymbols: true,       // Want colored line symbols?
    useColorForRealtimeInfo: true,      // Want colored real time information (delay, early)?
    showTableHeaders: true,             // Show table headers?
    showTableHeadersAsSymbols: true,    // Table Headers as symbols or written?
    maxUnreachableDepartures: 3,        // How many unreachable departures should be shown?
    maxReachableDepartures: 7,          // How many reachable departures should be shown?
    fadeUnreachableDepartures: true,    // Should unreachable departures be faded away from the reachable departures line?
    fadeReachableDepartures: true,      // Should reachable departures be faded away from the reachable departures line?
    fadePointForReachableDepartures: 0.25, // The point to start fading the reachable departures
    excludeDelayFromTimeLabel: false     // Should the delay time be excluded from the time label?
  },

  start: function () {
    Log.info("Starting module: " + this.name);

    this.departuresArray = [];
    this.stationName = "";
    this.loaded = false;
    this.error = {};

    // If the stationId is not a string, we'll print a warning
    if (typeof this.config.stationId === "number") {
      let warning = "MMM-PublicTransportBerlin deprecation warning: The stationId must be a String! Please check your configuration!";
      Log.warn(warning);
      console.log(warning);
    }

    // Provide backwards compatibility for refactoring of config.delay to config.travelTimeToStation
    if (this.config.delay) {
      let warning = "MMM-PublicTransportBerlin deprecation warning: The delay option has been renamed to travelTimeToStation. Please change your configuration!";
      Log.warn(warning);
      console.log(warning);

      this.config.travelTimeToStation = this.config.delay;
    }

    this.sendSocketNotification("CREATE_FETCHER", this.config);

    if(this.config.travelTimeToStation < 0) {
      this.config.travelTimeToStation = 0;
    }

    if(typeof this.config.ignoredLines === "undefined") {
      this.config.ignoredLines = [];
    }

    // set minimum interval to 30 seconds
    if (this.config.interval < 30000) {
      this.config.interval = 30000;
    }

    setInterval(() => {
      // If the module started without getting the stationName for some reason, we try to get the stationName again
      if(this.loaded && this.stationName === ""){
          this.sendSocketNotification("STATION_NAME_MISSING_AFTER_INIT", this.config.stationId);
      }

      this.sendSocketNotification("GET_DEPARTURES", this.config.stationId);
    }, this.config.interval)
  },

  getDom: function () {

    let wrapper = document.createElement("div");
    wrapper.className = "ptbWrapper";

    // Handle loading sequence at init time
    if (this.departuresArray.length === 0 && !this.loaded) {
      wrapper.innerHTML = (this.loaded) ? this.translate("EMPTY") : this.translate("LOADING");
      wrapper.className = "small light dimmed";
      return wrapper;
    }

    let heading = document.createElement("header");
    heading.innerHTML = this.stationName;
    wrapper.appendChild(heading);

    // Handle departure fetcher error and show it on the screen
    if (Object.keys(this.error).length > 0) {
      let errorContent = document.createElement("div");
      errorContent.innerHTML = this.translate("FETCHER_ERROR") + ": " + JSON.stringify(this.error.message) + "<br>";
      errorContent.innerHTML += this.translate("NO_VBBDATA_ERROR_HINT");
      errorContent.className = "small light dimmed errorCell";
      wrapper.appendChild(errorContent);
      return wrapper;
    }

    // Table header
    let table = document.createElement("table");
    table.className = "ptbTable small light";

    let tHead = document.createElement("thead");

    let headerRow = document.createElement("tr");

    // Cell for departure time
    let headerTime = document.createElement("td");
    headerTime.className = "centeredTd";

    if (this.config.showTableHeadersAsSymbols) {
      let timeIcon = document.createElement("span");
      timeIcon.className = "fa fa-clock-o";
      headerTime.appendChild(timeIcon);
    } else {
      headerTime.innerHTML = this.translate("WHEN");
    }

    headerRow.appendChild(headerTime);

    // Cell for travelTimeToStation time
    let delayTime = document.createElement("td");
    delayTime.innerHTML = " ";
    headerRow.appendChild(delayTime);

    // Cell for line symbol
    let headerLine = document.createElement("td");
    headerLine.className = "centeredTd";

    if (this.config.showTableHeadersAsSymbols) {
      let lineIcon = document.createElement("span");
      lineIcon.className = "fa fa-tag";
      headerLine.appendChild(lineIcon);
    } else {
      headerLine.innerHTML = this.translate("LINE");
    }

    headerRow.appendChild(headerLine);

    // Cell for direction
    let headerDirection = document.createElement("td");
    headerDirection.className = "centeredTd";

    if (this.config.showTableHeadersAsSymbols) {
      let directionIcon = document.createElement("span");
      directionIcon.className = "fa fa-exchange";
      headerDirection.appendChild(directionIcon);
    } else {
      headerDirection.innerHTML = this.translate("DIRECTION");
    }

    headerRow.appendChild(headerDirection);

    headerRow.className = "bold dimmed";

    if (this.config.showTableHeaders) {
      tHead.appendChild(headerRow);
    }

    table.appendChild(tHead);

    // Create table body from data
    let tBody = document.createElement("tbody");

    // Handle empty departures array
    if (this.departuresArray.length === 0) {
      let row = this.getNoDeparturesRow(this.translate("NO_DEPARTURES_AVAILABLE"));

      tBody.appendChild(row);
      table.appendChild(tBody);
      wrapper.appendChild(table);

      return wrapper;
    }

    // handle travelTimeToStation === 0
    if (this.config.travelTimeToStation === 0) {
        this.departuresArray.forEach((current, i) => {
            if (i < this.config.maxReachableDepartures) {
                let row = this.getRow(current);
                tBody.appendChild(row);

                // fading
                if (this.config.fadeReachableDepartures && this.config.fadePointForReachableDepartures < 1) {
                    if (this.config.fadePointForReachableDepartures < 0) {
                        this.config.fadePointForReachableDepartures = 0;
                    }
                    let startingPoint = this.config.maxReachableDepartures * this.config.fadePointForReachableDepartures;
                    let steps = this.config.maxReachableDepartures - startingPoint;
                    if (i >= startingPoint) {
                        let currentStep = i - startingPoint;
                        row.style.opacity = 1 - (1 / steps * currentStep);
                    }
                }
            }
        });
      // handle travelTimeToStation > 0
    } else {
        this.getFirstReachableDeparturePosition().then((reachableDeparturePos) => {
            this.departuresArray.forEach((current, i) => {

                if (i >= reachableDeparturePos - this.config.maxUnreachableDepartures
                    && i < reachableDeparturePos + this.config.maxReachableDepartures) {

                    // insert rule to separate reachable departures
                    if (i === reachableDeparturePos
                        && reachableDeparturePos !== 0
                        && this.config.maxUnreachableDepartures !== 0) {

                        let ruleRow = document.createElement("tr");

                        let ruleTimeCell = document.createElement("td");
                        ruleRow.appendChild(ruleTimeCell);

                        let ruleCell = document.createElement("td");
                        ruleCell.colSpan = 3;
                        ruleCell.className = "ruleCell";
                        ruleRow.appendChild(ruleCell);

                        tBody.appendChild(ruleRow);
                    }

                    // create standard row
                    let row = this.getRow(current);

                    // fading for entries before "travelTimeToStation rule"
                    if (this.config.fadeUnreachableDepartures && this.config.travelTimeToStation > 0) {
                        let steps = this.config.maxUnreachableDepartures;
                        if (i >= reachableDeparturePos - steps && i < reachableDeparturePos) {
                            let currentStep = reachableDeparturePos - i;
                            row.style.opacity = 1 - ((1 / steps * currentStep) - 0.2);
                        }
                    }

                    // fading for entries after "travelTimeToStation rule"
                    if (this.config.fadeReachableDepartures && this.config.fadePointForReachableDepartures < 1) {
                        if (this.config.fadePointForReachableDepartures < 0) {
                            this.config.fadePointForReachableDepartures = 0;
                        }
                        let startingPoint = this.config.maxReachableDepartures * this.config.fadePointForReachableDepartures;
                        let steps = this.config.maxReachableDepartures - startingPoint;
                        if (i >= reachableDeparturePos + startingPoint) {
                            let currentStep = (i - reachableDeparturePos) - startingPoint;
                            row.style.opacity = 1 - (1 / steps * currentStep);
                        }
                    }

                    tBody.appendChild(row);
                }
            });
        }, (message) => {
            let row = this.getNoDeparturesRow(message);
            tBody.appendChild(row);
        });
    }

    table.appendChild(tBody);

    wrapper.appendChild(table);

    return wrapper;
  },

  getNoDeparturesRow: function (message) {
    let row = document.createElement("tr");
    let cell = document.createElement("td");
    cell.colSpan = 4;

    cell.innerHTML = message;

    row.appendChild(cell);

    return row;
  },

  getRow: function (current) {

    let currentWhen = moment(current.when);
    let delay = this.convertDelayToMinutes(current.delay);

    if (this.config.excludeDelayFromTimeLabel) {
      currentWhen = this.getDepartureTimeWithoutDelay(currentWhen, delay);
    }

    let row = document.createElement("tr");

    let timeCell = document.createElement("td");
    timeCell.className = "centeredTd timeCell";
    timeCell.innerHTML = currentWhen.format("HH:mm");
    row.appendChild(timeCell);

    let delayCell = document.createElement("td");
    delayCell.className = "delayTimeCell";

    if (delay > 0) {
      delayCell.innerHTML = "+" + delay + " ";
      if (this.config.useColorForRealtimeInfo) {
          delayCell.style.color = "red";
      }
    } else if (delay < 0) {
      delayCell.innerHTML = delay + " ";
      if (this.config.useColorForRealtimeInfo) {
          delayCell.style.color = "green";
      }
    } else if (delay === 0) {
      delayCell.innerHTML = "";
    }

    row.appendChild(delayCell);

    let lineCell = document.createElement("td");
    let lineSymbol = this.getLineSymbol(current);
    lineCell.className = "centeredTd noPadding lineCell";

    lineCell.appendChild(lineSymbol);
    row.appendChild(lineCell);

    let directionCell = document.createElement("td");
    directionCell.className = "directionCell";

    if (this.config.marqueeLongDirections && current.direction.length >= 26) {
      directionCell.className = "directionCell marquee";
      let directionSpan = document.createElement("span");
      directionSpan.innerHTML = current.direction;
      directionCell.appendChild(directionSpan);
    } else {
      directionCell.innerHTML = this.trimDirectionString(current.direction);
    }

    row.appendChild(directionCell);

    // Add cancelled class to this row if the trip was cancelled
    if (current.cancelled) {
        row.classList.add("cancelled");
    }

    return row;
  },

  getDepartureTimeWithoutDelay: function (departureTime, delay) {
    if (delay > 0) {
      departureTime.subtract(delay, "minutes");
    } else if (delay < 0) {
      departureTime.add(Math.abs(delay), "minutes");
    }

    return departureTime;
  },

  getFirstReachableDeparturePosition: function () {
    let now = moment();
    let nowWithDelay = now.add(this.config.travelTimeToStation, "minutes");

    return new Promise((resolve, reject) => {
      this.departuresArray.forEach((current, i, depArray) => {

        let currentWhen = moment(current.when);

        if (depArray.length > 1 && i < depArray.length - 1) {

          let nextWhen = moment(depArray[i + 1].when);
          if ((currentWhen.isBefore(nowWithDelay) && nextWhen.isSameOrAfter(nowWithDelay))
              || (i === 0 && nextWhen.isSameOrAfter(nowWithDelay))) {

              resolve(i);
          }
        } else if (i === depArray.length - 1 && currentWhen.isBefore(nowWithDelay)) {
          reject(this.translate("NO_REACHABLE_DEPARTURES"));
        } else {
          reject(this.translate("NO_REACHABLE_DEPARTURES"));
        }
      });
    });
  },

  trimDirectionString: function (string) {
    let dirString = string;

    if (dirString.indexOf(",") > -1) {
      dirString = dirString.split(",")[0]
    }

    let viaIndex = dirString.search(/( via )/g);
    if (viaIndex > -1) {
      dirString = dirString.split(/( via )/g)[0]
    }

    return dirString
  },

  getLineSymbol: function (product) {
    let symbol = document.createElement("div");

    if (product.type === "express") {
      if (product.name === "LOCOMORE")
        symbol.innerHTML = "LOC";
      else
        symbol.innerHTML = "ICE";

    } else if (product.type === "bus" || product.type == "tram") {
      symbol.innerHTML = product.name.split(" ")[1]
    } else {
      symbol.innerHTML = product.name;
    }

    symbol.classList.add(product.cssClass);
    symbol.classList.add("xsmall");

    if (this.config.showColoredLineSymbols) {
      symbol.style.backgroundColor = product.color;
    } else {
      symbol.style.backgroundColor = "#333333";
    }

    return symbol;
  },

  convertDelayToMinutes: function (delay) {
      return Math.floor((((delay % 31536000) % 86400) % 3600) / 60);
  },

  getTranslations: function() {
    return {
      en: "translations/en.json",
      de: "translations/de.json"
    }
  },

  getStyles: function () {
    return [
      "style.css",
      "font-awesome.css"
    ];
  },

  getScripts: function () {
    return [
      "moment.js"
    ];
},

socketNotificationReceived: function (notification, payload) {
  if (notification === "FETCHER_INIT") {
    if (payload.stationId === this.config.stationId) {
      this.stationName = payload.stationName;
      this.loaded = true;
      }
    }

    if (notification === "DEPARTURES") {
      if (payload.stationId === this.config.stationId) {
        this.loaded = true;
        // Empty error object
        this.error = {};
        // Proceed with normal operation
        this.departuresArray = payload.departuresArray;
        this.updateDom(3000);
      }
    }

    if (notification === "FETCH_ERROR") {
      if (payload.stationId === this.config.stationId) {
        this.loaded = true;
        this.error = payload;
        this.updateDom(3000);
      }
    }
  }
});
<commit_msg>Fixed wrong double equal to triple equal<commit_after>"use strict";

Module.register("MMM-PublicTransportBerlin", {
  // default values
  defaults: {
    name: "MMM-PublicTransportBerlin",  // The name of this module
    hidden: false,                      // Hide this module?
    stationId: "900000160003",          // The ID of the station
 //   directionStationId: 0,             // The stationId of the next station in which direction departures should be shown
    ignoredStations: [],                // Which stations should be ignored? (comma-separated list of station IDs)
    ignoredLines: [],                   // Which lines should be ignored? (comma-separated list of line names)
    excludedTransportationTypes: "",    // Which transportation types should not be shown on the mirror? (comma-separated list of types) possible values: bus,tram,suburban,subway,ferry
    marqueeLongDirections: true,        // Use Marquee effect for long station names?
    travelTimeToStation: 10,            // How long do you need to walk/bike to the next Station?
    interval: 120000,                   // How often should the table be updated in ms?
    departureMinutes: 30,               // For how many minutes should departures be shown?
    showColoredLineSymbols: true,       // Want colored line symbols?
    useColorForRealtimeInfo: true,      // Want colored real time information (delay, early)?
    showTableHeaders: true,             // Show table headers?
    showTableHeadersAsSymbols: true,    // Table Headers as symbols or written?
    maxUnreachableDepartures: 3,        // How many unreachable departures should be shown?
    maxReachableDepartures: 7,          // How many reachable departures should be shown?
    fadeUnreachableDepartures: true,    // Should unreachable departures be faded away from the reachable departures line?
    fadeReachableDepartures: true,      // Should reachable departures be faded away from the reachable departures line?
    fadePointForReachableDepartures: 0.25, // The point to start fading the reachable departures
    excludeDelayFromTimeLabel: false     // Should the delay time be excluded from the time label?
  },

  start: function () {
    Log.info("Starting module: " + this.name);

    this.departuresArray = [];
    this.stationName = "";
    this.loaded = false;
    this.error = {};

    // If the stationId is not a string, we'll print a warning
    if (typeof this.config.stationId === "number") {
      let warning = "MMM-PublicTransportBerlin deprecation warning: The stationId must be a String! Please check your configuration!";
      Log.warn(warning);
      console.log(warning);
    }

    // Provide backwards compatibility for refactoring of config.delay to config.travelTimeToStation
    if (this.config.delay) {
      let warning = "MMM-PublicTransportBerlin deprecation warning: The delay option has been renamed to travelTimeToStation. Please change your configuration!";
      Log.warn(warning);
      console.log(warning);

      this.config.travelTimeToStation = this.config.delay;
    }

    this.sendSocketNotification("CREATE_FETCHER", this.config);

    if(this.config.travelTimeToStation < 0) {
      this.config.travelTimeToStation = 0;
    }

    if(typeof this.config.ignoredLines === "undefined") {
      this.config.ignoredLines = [];
    }

    // set minimum interval to 30 seconds
    if (this.config.interval < 30000) {
      this.config.interval = 30000;
    }

    setInterval(() => {
      // If the module started without getting the stationName for some reason, we try to get the stationName again
      if(this.loaded && this.stationName === ""){
          this.sendSocketNotification("STATION_NAME_MISSING_AFTER_INIT", this.config.stationId);
      }

      this.sendSocketNotification("GET_DEPARTURES", this.config.stationId);
    }, this.config.interval)
  },

  getDom: function () {

    let wrapper = document.createElement("div");
    wrapper.className = "ptbWrapper";

    // Handle loading sequence at init time
    if (this.departuresArray.length === 0 && !this.loaded) {
      wrapper.innerHTML = (this.loaded) ? this.translate("EMPTY") : this.translate("LOADING");
      wrapper.className = "small light dimmed";
      return wrapper;
    }

    let heading = document.createElement("header");
    heading.innerHTML = this.stationName;
    wrapper.appendChild(heading);

    // Handle departure fetcher error and show it on the screen
    if (Object.keys(this.error).length > 0) {
      let errorContent = document.createElement("div");
      errorContent.innerHTML = this.translate("FETCHER_ERROR") + ": " + JSON.stringify(this.error.message) + "<br>";
      errorContent.innerHTML += this.translate("NO_VBBDATA_ERROR_HINT");
      errorContent.className = "small light dimmed errorCell";
      wrapper.appendChild(errorContent);
      return wrapper;
    }

    // Table header
    let table = document.createElement("table");
    table.className = "ptbTable small light";

    let tHead = document.createElement("thead");

    let headerRow = document.createElement("tr");

    // Cell for departure time
    let headerTime = document.createElement("td");
    headerTime.className = "centeredTd";

    if (this.config.showTableHeadersAsSymbols) {
      let timeIcon = document.createElement("span");
      timeIcon.className = "fa fa-clock-o";
      headerTime.appendChild(timeIcon);
    } else {
      headerTime.innerHTML = this.translate("WHEN");
    }

    headerRow.appendChild(headerTime);

    // Cell for travelTimeToStation time
    let delayTime = document.createElement("td");
    delayTime.innerHTML = " ";
    headerRow.appendChild(delayTime);

    // Cell for line symbol
    let headerLine = document.createElement("td");
    headerLine.className = "centeredTd";

    if (this.config.showTableHeadersAsSymbols) {
      let lineIcon = document.createElement("span");
      lineIcon.className = "fa fa-tag";
      headerLine.appendChild(lineIcon);
    } else {
      headerLine.innerHTML = this.translate("LINE");
    }

    headerRow.appendChild(headerLine);

    // Cell for direction
    let headerDirection = document.createElement("td");
    headerDirection.className = "centeredTd";

    if (this.config.showTableHeadersAsSymbols) {
      let directionIcon = document.createElement("span");
      directionIcon.className = "fa fa-exchange";
      headerDirection.appendChild(directionIcon);
    } else {
      headerDirection.innerHTML = this.translate("DIRECTION");
    }

    headerRow.appendChild(headerDirection);

    headerRow.className = "bold dimmed";

    if (this.config.showTableHeaders) {
      tHead.appendChild(headerRow);
    }

    table.appendChild(tHead);

    // Create table body from data
    let tBody = document.createElement("tbody");

    // Handle empty departures array
    if (this.departuresArray.length === 0) {
      let row = this.getNoDeparturesRow(this.translate("NO_DEPARTURES_AVAILABLE"));

      tBody.appendChild(row);
      table.appendChild(tBody);
      wrapper.appendChild(table);

      return wrapper;
    }

    // handle travelTimeToStation === 0
    if (this.config.travelTimeToStation === 0) {
        this.departuresArray.forEach((current, i) => {
            if (i < this.config.maxReachableDepartures) {
                let row = this.getRow(current);
                tBody.appendChild(row);

                // fading
                if (this.config.fadeReachableDepartures && this.config.fadePointForReachableDepartures < 1) {
                    if (this.config.fadePointForReachableDepartures < 0) {
                        this.config.fadePointForReachableDepartures = 0;
                    }
                    let startingPoint = this.config.maxReachableDepartures * this.config.fadePointForReachableDepartures;
                    let steps = this.config.maxReachableDepartures - startingPoint;
                    if (i >= startingPoint) {
                        let currentStep = i - startingPoint;
                        row.style.opacity = 1 - (1 / steps * currentStep);
                    }
                }
            }
        });
      // handle travelTimeToStation > 0
    } else {
        this.getFirstReachableDeparturePosition().then((reachableDeparturePos) => {
            this.departuresArray.forEach((current, i) => {

                if (i >= reachableDeparturePos - this.config.maxUnreachableDepartures
                    && i < reachableDeparturePos + this.config.maxReachableDepartures) {

                    // insert rule to separate reachable departures
                    if (i === reachableDeparturePos
                        && reachableDeparturePos !== 0
                        && this.config.maxUnreachableDepartures !== 0) {

                        let ruleRow = document.createElement("tr");

                        let ruleTimeCell = document.createElement("td");
                        ruleRow.appendChild(ruleTimeCell);

                        let ruleCell = document.createElement("td");
                        ruleCell.colSpan = 3;
                        ruleCell.className = "ruleCell";
                        ruleRow.appendChild(ruleCell);

                        tBody.appendChild(ruleRow);
                    }

                    // create standard row
                    let row = this.getRow(current);

                    // fading for entries before "travelTimeToStation rule"
                    if (this.config.fadeUnreachableDepartures && this.config.travelTimeToStation > 0) {
                        let steps = this.config.maxUnreachableDepartures;
                        if (i >= reachableDeparturePos - steps && i < reachableDeparturePos) {
                            let currentStep = reachableDeparturePos - i;
                            row.style.opacity = 1 - ((1 / steps * currentStep) - 0.2);
                        }
                    }

                    // fading for entries after "travelTimeToStation rule"
                    if (this.config.fadeReachableDepartures && this.config.fadePointForReachableDepartures < 1) {
                        if (this.config.fadePointForReachableDepartures < 0) {
                            this.config.fadePointForReachableDepartures = 0;
                        }
                        let startingPoint = this.config.maxReachableDepartures * this.config.fadePointForReachableDepartures;
                        let steps = this.config.maxReachableDepartures - startingPoint;
                        if (i >= reachableDeparturePos + startingPoint) {
                            let currentStep = (i - reachableDeparturePos) - startingPoint;
                            row.style.opacity = 1 - (1 / steps * currentStep);
                        }
                    }

                    tBody.appendChild(row);
                }
            });
        }, (message) => {
            let row = this.getNoDeparturesRow(message);
            tBody.appendChild(row);
        });
    }

    table.appendChild(tBody);

    wrapper.appendChild(table);

    return wrapper;
  },

  getNoDeparturesRow: function (message) {
    let row = document.createElement("tr");
    let cell = document.createElement("td");
    cell.colSpan = 4;

    cell.innerHTML = message;

    row.appendChild(cell);

    return row;
  },

  getRow: function (current) {

    let currentWhen = moment(current.when);
    let delay = this.convertDelayToMinutes(current.delay);

    if (this.config.excludeDelayFromTimeLabel) {
      currentWhen = this.getDepartureTimeWithoutDelay(currentWhen, delay);
    }

    let row = document.createElement("tr");

    let timeCell = document.createElement("td");
    timeCell.className = "centeredTd timeCell";
    timeCell.innerHTML = currentWhen.format("HH:mm");
    row.appendChild(timeCell);

    let delayCell = document.createElement("td");
    delayCell.className = "delayTimeCell";

    if (delay > 0) {
      delayCell.innerHTML = "+" + delay + " ";
      if (this.config.useColorForRealtimeInfo) {
          delayCell.style.color = "red";
      }
    } else if (delay < 0) {
      delayCell.innerHTML = delay + " ";
      if (this.config.useColorForRealtimeInfo) {
          delayCell.style.color = "green";
      }
    } else if (delay === 0) {
      delayCell.innerHTML = "";
    }

    row.appendChild(delayCell);

    let lineCell = document.createElement("td");
    let lineSymbol = this.getLineSymbol(current);
    lineCell.className = "centeredTd noPadding lineCell";

    lineCell.appendChild(lineSymbol);
    row.appendChild(lineCell);

    let directionCell = document.createElement("td");
    directionCell.className = "directionCell";

    if (this.config.marqueeLongDirections && current.direction.length >= 26) {
      directionCell.className = "directionCell marquee";
      let directionSpan = document.createElement("span");
      directionSpan.innerHTML = current.direction;
      directionCell.appendChild(directionSpan);
    } else {
      directionCell.innerHTML = this.trimDirectionString(current.direction);
    }

    row.appendChild(directionCell);

    // Add cancelled class to this row if the trip was cancelled
    if (current.cancelled) {
        row.classList.add("cancelled");
    }

    return row;
  },

  getDepartureTimeWithoutDelay: function (departureTime, delay) {
    if (delay > 0) {
      departureTime.subtract(delay, "minutes");
    } else if (delay < 0) {
      departureTime.add(Math.abs(delay), "minutes");
    }

    return departureTime;
  },

  getFirstReachableDeparturePosition: function () {
    let now = moment();
    let nowWithDelay = now.add(this.config.travelTimeToStation, "minutes");

    return new Promise((resolve, reject) => {
      this.departuresArray.forEach((current, i, depArray) => {

        let currentWhen = moment(current.when);

        if (depArray.length > 1 && i < depArray.length - 1) {

          let nextWhen = moment(depArray[i + 1].when);
          if ((currentWhen.isBefore(nowWithDelay) && nextWhen.isSameOrAfter(nowWithDelay))
              || (i === 0 && nextWhen.isSameOrAfter(nowWithDelay))) {

              resolve(i);
          }
        } else if (i === depArray.length - 1 && currentWhen.isBefore(nowWithDelay)) {
          reject(this.translate("NO_REACHABLE_DEPARTURES"));
        } else {
          reject(this.translate("NO_REACHABLE_DEPARTURES"));
        }
      });
    });
  },

  trimDirectionString: function (string) {
    let dirString = string;

    if (dirString.indexOf(",") > -1) {
      dirString = dirString.split(",")[0]
    }

    let viaIndex = dirString.search(/( via )/g);
    if (viaIndex > -1) {
      dirString = dirString.split(/( via )/g)[0]
    }

    return dirString
  },

  getLineSymbol: function (product) {
    let symbol = document.createElement("div");

    if (product.type === "express") {
      if (product.name === "LOCOMORE")
        symbol.innerHTML = "LOC";
      else
        symbol.innerHTML = "ICE";

    } else if (product.type === "bus" || product.type === "tram") {
      symbol.innerHTML = product.name.split(" ")[1]
    } else {
      symbol.innerHTML = product.name;
    }

    symbol.classList.add(product.cssClass);
    symbol.classList.add("xsmall");

    if (this.config.showColoredLineSymbols) {
      symbol.style.backgroundColor = product.color;
    } else {
      symbol.style.backgroundColor = "#333333";
    }

    return symbol;
  },

  convertDelayToMinutes: function (delay) {
      return Math.floor((((delay % 31536000) % 86400) % 3600) / 60);
  },

  getTranslations: function() {
    return {
      en: "translations/en.json",
      de: "translations/de.json"
    }
  },

  getStyles: function () {
    return [
      "style.css",
      "font-awesome.css"
    ];
  },

  getScripts: function () {
    return [
      "moment.js"
    ];
},

socketNotificationReceived: function (notification, payload) {
  if (notification === "FETCHER_INIT") {
    if (payload.stationId === this.config.stationId) {
      this.stationName = payload.stationName;
      this.loaded = true;
      }
    }

    if (notification === "DEPARTURES") {
      if (payload.stationId === this.config.stationId) {
        this.loaded = true;
        // Empty error object
        this.error = {};
        // Proceed with normal operation
        this.departuresArray = payload.departuresArray;
        this.updateDom(3000);
      }
    }

    if (notification === "FETCH_ERROR") {
      if (payload.stationId === this.config.stationId) {
        this.loaded = true;
        this.error = payload;
        this.updateDom(3000);
      }
    }
  }
});
<|endoftext|>


<commit_before>function Arena(args) {
    args = args || {};
    var players = args.playersList || new PlayersList(args.playersListOptions);
    var arenaHandler = args.arena || "arena";
    var arena = document.getElementById(arenaHandler);
    var drawingContext;

    (function init() {
        var canvas = document.createElement("canvas");
        arena.appendChild(canvas);

        drawingContext = canvas.getContext("2d");
    })();

    var addNewPlayer = function (who) {
        players.addNewPlayer(who);
        drawingContext.strokeStyle = "#F00";
        drawingContext.fillStyle = "#F00";
        drawingContext.arc(who.Position.X, who.Position.Y, who.Size, 0, 2 * Math.PI);
        drawingContext.stroke();
        drawingContext.fill();
    }

    return {
        addNewPlayer: addNewPlayer,
    };
};<commit_msg>initialize players list in constructor<commit_after>function Arena(args) {
    args = args || {};
    var players;
    var arenaHandler = args.arena || "arena";
    var arena = document.getElementById(arenaHandler);
    var drawingContext;

    (function init() {
        players = args.playersList || new PlayersList(args.playersListOptions);
        var canvas = document.createElement("canvas");
        arena.appendChild(canvas);

        drawingContext = canvas.getContext("2d");
    })();

    var addNewPlayer = function (who) {
        players.addNewPlayer(who);
        drawingContext.strokeStyle = "#F00";
        drawingContext.fillStyle = "#F00";
        drawingContext.arc(who.Position.X, who.Position.Y, who.Size, 0, 2 * Math.PI);
        drawingContext.stroke();
        drawingContext.fill();
    }

    return {
        addNewPlayer: addNewPlayer,
    };
};<|endoftext|>