<commit_before>/**
 * @fileoverview This file defines the geolocation control.
 *
 */

goog.require('ol.Feature');
goog.require('ol.FeatureOverlay');
goog.require('ol.Geolocation');
goog.require('ol.control.Control');

goog.provide('app.LocationControl');

/**
 * @typedef {{className: (string|undefined),
 *     label: (string|undefined),
 *     tipLabel: (string|undefined),
 *     target: (Element|undefined)
 * }}
 */
app.LocationControlOptions;

/**
 * @constructor
 * @extends {ol.control.Control}
 * @param {app.LocationControlOptions=} opt_options Location Control
 * options.
 */
app.LocationControl = function(opt_options) {

  var options = goog.isDef(opt_options) ? opt_options : {};
  var className = goog.isDef(options.className) ? options.className :
      'location-button';
  /**
   * @type {?ol.Geolocation}
   * @private
   */
  this.geolocation_ = null;
  /**
   * @type {?ol.FeatureOverlay}
   * @private
   */
  this.featureOverlay_ = null;
  this.positionPoint_ = new ol.geom.Point([0, 0]);

  var label = goog.isDef(options.label) ? options.label : 'L';
  var tipLabel = goog.isDef(options.tipLabel) ?
      options.tipLabel : 'Location';
  var button = goog.dom.createDom(goog.dom.TagName.BUTTON, {
    'type': 'button',
    'title': tipLabel
  }, label);

  var cssClasses = className + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' +
      ol.css.CLASS_CONTROL + ' ' + 'tracker-off';

  /**
   * @type {!Element}
   */
  this.element = goog.dom.createDom(goog.dom.TagName.DIV, cssClasses, button);

  goog.events.listen(button, goog.events.EventType.CLICK,
      this.handleClick_, false, this);

  goog.events.listen(button, [
    goog.events.EventType.MOUSEOUT,
    goog.events.EventType.FOCUSOUT
  ], function() {
    this.blur();
  }, false);

  goog.base(this, {
    element: this.element,
    target: options.target
  });

};
goog.inherits(app.LocationControl, ol.control.Control);

/**
 * @param {goog.events.BrowserEvent} event The event to handle
 * @private
 */
app.LocationControl.prototype.handleClick_ = function(event) {
  event.preventDefault();
  this.handleCenterToLocation_();
};

/**
 * @private
 */
app.LocationControl.prototype.handleCenterToLocation_ = function() {
  if (goog.isNull(this.geolocation_)) {
    this.initGeoLocation_();
  }

  if (!this.geolocation_.getTracking()) {
    this.initFeatureOverlay_();
    this.getMap().getView().setZoom(17);
    this.geolocation_.setTracking(true);
  }else {
    this.clearFeatureOverlay_();
    this.geolocation_.setTracking(false);

  }
};

/**
 *
 * @private
 */
app.LocationControl.prototype.initGeoLocation_ = function() {

  var map = this.getMap();
  var view = map.getView();
  this.geolocation_ = /** @type {ol.Geolocation} */ (new ol.Geolocation({
    projection: view.getProjection()
  }));

  this.geolocation_.on('change:tracking', goog.bind(function(e) {

    if (this.geolocation_.getTracking()) {
      goog.dom.classlist.swap(this.element, 'tracker-off', 'tracker-on');
    }else {
      goog.dom.classlist.swap(this.element, 'tracker-on', 'tracker-off');
    }
  },this));
  this.geolocation_.on('change:position', goog.bind(function(e) {
    var position = /** @type {ol.Coordinate} */
        (this.geolocation_.getPosition());

    this.positionPoint_.setCoordinates(position);
    view.setCenter(position);
  },this));
};

/**
 *
 * @private
 */
app.LocationControl.prototype.initFeatureOverlay_ = function() {

  var map = this.getMap();
  var positionFeature = new ol.Feature(this.positionPoint_);

  var accuracyFeature = new ol.Feature();
  accuracyFeature.bindTo('geometry', this.geolocation_, 'accuracyGeometry');

  this.featureOverlay_ = new ol.FeatureOverlay({
    features: [positionFeature, accuracyFeature]
  });
  this.featureOverlay_.setMap(map);
};

/**
 *
 * @private
 */
app.LocationControl.prototype.clearFeatureOverlay_ = function() {
  if (this.featureOverlay_ != null) {
    var features = this.featureOverlay_.getFeatures();
    if (features != null) {
      features.clear();
    }
  }
};
<commit_msg>? is useless for object type annotation<commit_after>/**
 * @fileoverview This file defines the geolocation control.
 *
 */

goog.require('ol.Feature');
goog.require('ol.FeatureOverlay');
goog.require('ol.Geolocation');
goog.require('ol.control.Control');

goog.provide('app.LocationControl');

/**
 * @typedef {{className: (string|undefined),
 *     label: (string|undefined),
 *     tipLabel: (string|undefined),
 *     target: (Element|undefined)
 * }}
 */
app.LocationControlOptions;

/**
 * @constructor
 * @extends {ol.control.Control}
 * @param {app.LocationControlOptions=} opt_options Location Control
 * options.
 */
app.LocationControl = function(opt_options) {

  var options = goog.isDef(opt_options) ? opt_options : {};
  var className = goog.isDef(options.className) ? options.className :
      'location-button';

  /**
   * @type {ol.Geolocation}
   * @private
   */
  this.geolocation_ = null;

  /**
   * @type {ol.FeatureOverlay}
   * @private
   */
  this.featureOverlay_ = null;
  this.positionPoint_ = new ol.geom.Point([0, 0]);

  var label = goog.isDef(options.label) ? options.label : 'L';
  var tipLabel = goog.isDef(options.tipLabel) ?
      options.tipLabel : 'Location';
  var button = goog.dom.createDom(goog.dom.TagName.BUTTON, {
    'type': 'button',
    'title': tipLabel
  }, label);

  var cssClasses = className + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' +
      ol.css.CLASS_CONTROL + ' ' + 'tracker-off';

  /**
   * @type {!Element}
   */
  this.element = goog.dom.createDom(goog.dom.TagName.DIV, cssClasses, button);

  goog.events.listen(button, goog.events.EventType.CLICK,
      this.handleClick_, false, this);

  goog.events.listen(button, [
    goog.events.EventType.MOUSEOUT,
    goog.events.EventType.FOCUSOUT
  ], function() {
    this.blur();
  }, false);

  goog.base(this, {
    element: this.element,
    target: options.target
  });

};
goog.inherits(app.LocationControl, ol.control.Control);

/**
 * @param {goog.events.BrowserEvent} event The event to handle
 * @private
 */
app.LocationControl.prototype.handleClick_ = function(event) {
  event.preventDefault();
  this.handleCenterToLocation_();
};

/**
 * @private
 */
app.LocationControl.prototype.handleCenterToLocation_ = function() {
  if (goog.isNull(this.geolocation_)) {
    this.initGeoLocation_();
  }

  if (!this.geolocation_.getTracking()) {
    this.initFeatureOverlay_();
    this.getMap().getView().setZoom(17);
    this.geolocation_.setTracking(true);
  }else {
    this.clearFeatureOverlay_();
    this.geolocation_.setTracking(false);

  }
};

/**
 *
 * @private
 */
app.LocationControl.prototype.initGeoLocation_ = function() {

  var map = this.getMap();
  var view = map.getView();
  this.geolocation_ = /** @type {ol.Geolocation} */ (new ol.Geolocation({
    projection: view.getProjection()
  }));

  this.geolocation_.on('change:tracking', goog.bind(function(e) {

    if (this.geolocation_.getTracking()) {
      goog.dom.classlist.swap(this.element, 'tracker-off', 'tracker-on');
    }else {
      goog.dom.classlist.swap(this.element, 'tracker-on', 'tracker-off');
    }
  },this));
  this.geolocation_.on('change:position', goog.bind(function(e) {
    var position = /** @type {ol.Coordinate} */
        (this.geolocation_.getPosition());

    this.positionPoint_.setCoordinates(position);
    view.setCenter(position);
  },this));
};

/**
 *
 * @private
 */
app.LocationControl.prototype.initFeatureOverlay_ = function() {

  var map = this.getMap();
  var positionFeature = new ol.Feature(this.positionPoint_);

  var accuracyFeature = new ol.Feature();
  accuracyFeature.bindTo('geometry', this.geolocation_, 'accuracyGeometry');

  this.featureOverlay_ = new ol.FeatureOverlay({
    features: [positionFeature, accuracyFeature]
  });
  this.featureOverlay_.setMap(map);
};

/**
 *
 * @private
 */
app.LocationControl.prototype.clearFeatureOverlay_ = function() {
  if (this.featureOverlay_ != null) {
    var features = this.featureOverlay_.getFeatures();
    if (features != null) {
      features.clear();
    }
  }
};
<|endoftext|>


<commit_before>import LeaderLine from 'leader-line';
import React from 'react';
import _get from 'lodash/get';

function shimPointAnchor (point) {
  return point instanceof Element
    ? LeaderLine.pointAnchor( point, { x: 0, y: 0 } )
    : LeaderLine.pointAnchor( document.body, point )
    ;
}

export default class Line extends React.Component {
  componentWillUnmount () {
    if (this.line) {
      this.line.remove();
    }
  }

  setupInstance (ref) {
    this.svg = ref;

    if (ref) {
      this.shouldInitLine();
    }
  }

  shouldComponentUpdate (nextProps) {
    this.shouldInitLine(nextProps);

    if (this.line) {
      if (this.props.start != nextProps.start)
        this.line.start = shimPointAnchor(nextProps.start);
      if (this.props.end != nextProps.end)
        this.line.end = shimPointAnchor(nextProps.end);
      this.line.position();
    }

    return false;
  }

  initLine ({ start, end, options }) {
    const startPoint = shimPointAnchor(start);
    const endPoint = shimPointAnchor(end);

    this.line = new LeaderLine({
      path: 'fluid',
      dash: true,
      ...options,
      start: startPoint,
      end: endPoint,
      disableViewBox: true,
      svg: this.svg
    });

    const { svg } = this.line.getProps();
    svg.leaderLine = this.line;

    if (typeof(this.props.onLoad) === 'function')
      this.props.onLoad(this.line);
  }

  shouldInitLine (nextProps) {
    if (this.line)
      return false;

    const start = _get(nextProps, 'start', this.props.start);
    const end = _get(nextProps, 'end', this.props.end);
    const options = _get(nextProps, 'options', this.props.options);

    if (this.svg && start && end)
      this.initLine({ start, end, options });

    return true;
  }

  render() {
    return <svg ref={ ref => this.setupInstance(ref) } />;
  }
}<commit_msg>Add prop float to Line<commit_after>import LeaderLine from 'leader-line';
import React from 'react';
import _get from 'lodash/get';

function shimPointAnchor (point) {
  return point instanceof Element
    ? LeaderLine.pointAnchor( point, { x: 0, y: 0 } )
    : LeaderLine.pointAnchor( document.body, point )
    ;
}

export default class Line extends React.Component {

  static defaultProps = {
    float: false,
  }

  componentWillUnmount () {
    if (this.line) {
      this.line.remove();
      this.line = null;
    }
  }

  setupInstance (ref) {
    this.svg = ref;

    if (ref) {
      this.shouldInitLine();
    }
  }

  shouldComponentUpdate (nextProps) {
    this.shouldInitLine(nextProps);

    if (this.line) {
      if (this.props.start != nextProps.start)
        this.line.start = shimPointAnchor(nextProps.start);
      if (this.props.end != nextProps.end)
        this.line.end = shimPointAnchor(nextProps.end);
      this.line.position();

      if (nextProps.float)
        this.svg.parentNode.appendChild(this.svg);
    }

    return false;
  }

  initLine ({ start, end, options }) {
    const startPoint = shimPointAnchor(start);
    const endPoint = shimPointAnchor(end);

    this.line = new LeaderLine({
      path: 'fluid',
      dash: true,
      ...options,
      start: startPoint,
      end: endPoint,
      disableViewBox: true,
      svg: this.svg
    });

    const { svg } = this.line.getProps();
    svg.leaderLine = this.line;

    if (typeof(this.props.onLoad) === 'function')
      this.props.onLoad(this.line);
  }

  shouldInitLine (nextProps) {
    if (this.line)
      return false;

    const start = _get(nextProps, 'start', this.props.start);
    const end = _get(nextProps, 'end', this.props.end);
    const options = _get(nextProps, 'options', this.props.options);

    if (this.svg && start && end)
      this.initLine({ start, end, options });

    return true;
  }

  render() {
    return <svg ref={ ref => this.setupInstance(ref) } />;
  }
}<|endoftext|>


<commit_before>
'use strict';

goog.provide('Blockly.Blocks.hedgehog');

goog.require('Blockly.Blocks');

/**
 * Common HSV hue for all blocks in this category.
 */
Blockly.Blocks.hedgehog.HUE = 60;

// Common Help URL for all blocks in this category
Blockly.Blocks.hedgehog.HELPURL = "http://hedgehog.pria.at/";

Blockly.Blocks['hedgehog_move'] = {
    init: function() {
        this.setColour(Blockly.Blocks.hedgehog.HUE);
        this.setHelpUrl(Blockly.Blocks.hedgehog.HELPURL);
        this.appendDummyInput()
            .appendField("move motor")
            .appendField(new Blockly.FieldNumber(0, 0, 3, 1), "port")
            .appendField(new Blockly.FieldDropdown([["forward", "fw"], ["backward", "bw"]]), "dir");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip('');
    }
};

Blockly.Blocks['hedgehog_read_analog'] = {
    init: function() {
        this.setColour(Blockly.Blocks.hedgehog.HUE);
        this.setHelpUrl(Blockly.Blocks.hedgehog.HELPURL);
        this.appendDummyInput()
            .appendField("read analog pin")
            .appendField(new Blockly.FieldNumber(8, 8, 15, 1), "port");
        this.setOutput(true, "Number");
        this.setTooltip('');
    }
};

Blockly.Blocks['hedgehog_read_digital'] = {
    init: function() {
        this.setColour(Blockly.Blocks.hedgehog.HUE);
        this.setHelpUrl(Blockly.Blocks.hedgehog.HELPURL);
        this.appendDummyInput()
            .appendField("read digital pin")
            .appendField(new Blockly.FieldNumber(0, 0, 7, 1), "port");
        this.setOutput(true, "Boolean");
        this.setTooltip('');
    }
};
<commit_msg>fix hedgehog toolbox color<commit_after>
'use strict';

goog.provide('Blockly.Blocks.hedgehog');

goog.require('Blockly.Blocks');

/**
 * Common HSV hue for all blocks in this category.
 */
Blockly.Blocks.hedgehog.HUE = 120;
Blockly.Blocks.loops.HUE = 60;

// Common Help URL for all blocks in this category
Blockly.Blocks.hedgehog.HELPURL = "http://hedgehog.pria.at/";

Blockly.Blocks['hedgehog_move'] = {
    init: function() {
        this.setColour(Blockly.Blocks.hedgehog.HUE);
        this.setHelpUrl(Blockly.Blocks.hedgehog.HELPURL);
        this.appendDummyInput()
            .appendField("move motor")
            .appendField(new Blockly.FieldNumber(0, 0, 3, 1), "port")
            .appendField(new Blockly.FieldDropdown([["forward", "fw"], ["backward", "bw"]]), "dir");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip('');
    }
};

Blockly.Blocks['hedgehog_read_analog'] = {
    init: function() {
        this.setColour(Blockly.Blocks.hedgehog.HUE);
        this.setHelpUrl(Blockly.Blocks.hedgehog.HELPURL);
        this.appendDummyInput()
            .appendField("read analog pin")
            .appendField(new Blockly.FieldNumber(8, 8, 15, 1), "port");
        this.setOutput(true, "Number");
        this.setTooltip('');
    }
};

Blockly.Blocks['hedgehog_read_digital'] = {
    init: function() {
        this.setColour(Blockly.Blocks.hedgehog.HUE);
        this.setHelpUrl(Blockly.Blocks.hedgehog.HELPURL);
        this.appendDummyInput()
            .appendField("read digital pin")
            .appendField(new Blockly.FieldNumber(0, 0, 7, 1), "port");
        this.setOutput(true, "Boolean");
        this.setTooltip('');
    }
};
<|endoftext|>


<commit_before>'use strict'

module.exports = [
  {
    user: 'U02AFEUJT',
    username: 'michal.brasna',
    services: ['tankovna', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U02U8LR8C',
    username: 'jan.pavlovsky',
    services: ['peters', 'meat-market', 'globus', 'lokal-hamburk', 'bad-flash-bar']
  },
  {
    user: 'UAQUTU63Z',
    username: 'alina',
    services: ['tankovna', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U4Y0SMG5P',
    username: 'jakub.loffelmann',
    services: ['tankovna', 'lokal-hamburk', 'globus', 'bad-flash-bar']
  },
  {
    user: 'U02AG6ZJW',
    username: 'ottokovarik',
    services: ['tankovna', 'lokal-hamburk', 'globus', 'bad-flash-bar']
  },
  {
    user: 'U02DFEYFU',
    username: 'radim',
    services: ['tankovna', 'lokal-hamburk', 'u-zabranskych']
  },
  {
    user: 'U02APJAFH',
    username: 'tomas.pokorny',
    services: ['tankovna', 'lokal-hamburk']
  },
  {
    user: 'U02AAGWQL',
    username: 'radek.carda',
    services: ['peters', 'globus', 'meat-market', 'lokal-hamburk']
  },
  {
    user: 'U02UQK6DW',
    username: 'zdenek.cejka',
    services: ['peters', 'tankovna', 'u-sani', 'meat-market', 'globus']
  },
  {
    user: 'U02A8R785',
    username: 'mafo',
    services: ['tankovna', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U02G1DFK5',
    username: 'martin.kadlec',
    services: ['tankovna', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U02AAEFEE',
    username: 'tomasbauer',
    services: ['tankovna', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U1N3KSXV5',
    username: 'snajby',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych']
  },
  {
    user: 'U02AKQ3N6',
    username: 'milan',
    services: ['peters', 'tankovna', 'u-sani', 'meat-market', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U0CGN045Q',
    username: 'vaclavhosticka',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych']
  },
  {
    user: 'U3YKTP9B3',
    username: 'ango',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-sani', 'u-tunelu']
  },
  {
    user: 'U4SRV3LUQ',
    username: 'ondram',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-sani', 'u-tunelu']
  },
  {
    user: 'U1X00FEPQ',
    username: 'jenism',
    services: ['peters', 'meat-market', 'globus', 'lokal-hamburk']
  },
  {
    user: 'U02A9M0QB',
    username: 'petrkrejcik',
    services: ['tankovna', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-tunelu']
  },
  {
    user: 'U02A54QBN',
    username: 'adamsobotka',
    services: ['tankovna', 'lokal-hamburk', 'meat-market', 'globus']
  },
  {
    user: 'U0FK93EE6',
    username: 'jakubsimecek',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-sani', 'u-tunelu']
  },
  {
    user: 'U8MCDASJX',
    username: 'renata.vostra',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-tunelu']
  },
  {
    user: 'U92CL53TP',
    username: 'martin.hrabovsky',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-tunelu']
  }
]
<commit_msg>Remove Cejka<commit_after>'use strict'

module.exports = [
  {
    user: 'U02AFEUJT',
    username: 'michal.brasna',
    services: ['tankovna', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U02U8LR8C',
    username: 'jan.pavlovsky',
    services: ['peters', 'meat-market', 'globus', 'lokal-hamburk', 'bad-flash-bar']
  },
  {
    user: 'UAQUTU63Z',
    username: 'alina',
    services: ['tankovna', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U4Y0SMG5P',
    username: 'jakub.loffelmann',
    services: ['tankovna', 'lokal-hamburk', 'globus', 'bad-flash-bar']
  },
  {
    user: 'U02AG6ZJW',
    username: 'ottokovarik',
    services: ['tankovna', 'lokal-hamburk', 'globus', 'bad-flash-bar']
  },
  {
    user: 'U02DFEYFU',
    username: 'radim',
    services: ['tankovna', 'lokal-hamburk', 'u-zabranskych']
  },
  {
    user: 'U02APJAFH',
    username: 'tomas.pokorny',
    services: ['tankovna', 'lokal-hamburk']
  },
  {
    user: 'U02AAGWQL',
    username: 'radek.carda',
    services: ['peters', 'globus', 'meat-market', 'lokal-hamburk']
  },
  {
    user: 'U02A8R785',
    username: 'mafo',
    services: ['tankovna', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U02G1DFK5',
    username: 'martin.kadlec',
    services: ['tankovna', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U02AAEFEE',
    username: 'tomasbauer',
    services: ['tankovna', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U1N3KSXV5',
    username: 'snajby',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych']
  },
  {
    user: 'U02AKQ3N6',
    username: 'milan',
    services: ['peters', 'tankovna', 'u-sani', 'meat-market', 'lokal-hamburk', 'globus']
  },
  {
    user: 'U0CGN045Q',
    username: 'vaclavhosticka',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych']
  },
  {
    user: 'U3YKTP9B3',
    username: 'ango',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-sani', 'u-tunelu']
  },
  {
    user: 'U4SRV3LUQ',
    username: 'ondram',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-sani', 'u-tunelu']
  },
  {
    user: 'U1X00FEPQ',
    username: 'jenism',
    services: ['peters', 'meat-market', 'globus', 'lokal-hamburk']
  },
  {
    user: 'U02A9M0QB',
    username: 'petrkrejcik',
    services: ['tankovna', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-tunelu']
  },
  {
    user: 'U02A54QBN',
    username: 'adamsobotka',
    services: ['tankovna', 'lokal-hamburk', 'meat-market', 'globus']
  },
  {
    user: 'U0FK93EE6',
    username: 'jakubsimecek',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-sani', 'u-tunelu']
  },
  {
    user: 'U8MCDASJX',
    username: 'renata.vostra',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-tunelu']
  },
  {
    user: 'U92CL53TP',
    username: 'martin.hrabovsky',
    services: ['peters', 'tankovna', 'meat-market', 'lokal-hamburk', 'globus', 'u-zabranskych', 'u-tunelu']
  }
]
<|endoftext|>


<commit_before>var PlayState = new Kiwi.State('PlayState');

/**
* The PlayState in the core state that is used in the game.
*
* It is the state where majority of the functionality occurs 'in-game' occurs.
*
*
* @class playState
* @extends State
* @constructor
*/

/**
* This create method is executed when Kiwi Game reaches the boot stage of the game loop.
* @method create
* @public
*/
PlayState.create = function () {

    //Switch the background colour back to white from purple
    this.game.stage.color = 'ffffff';

    //Variables relating to the state of the game
    this.gameStarted = false;
    this.gameEnded = false;

    //Values pertaining to physics based logic
    this.gravity = 1;
    this.xSpeed = 3;
    this.ySpeed = 0;
    this.maxYSpeed = 16;

    this.flapSpeed = -16;
    this.pipeDistance = 400;
    this.pipeGap = 260;

    //The starting coordinates of the bird.
    this.startX = (this.game.stage.width / 2) - 46
    this.startY = (this.game.stage.height / 2) - 64;

    //Background image
    this.bg = new Kiwi.GameObjects.Sprite(this, this.textures.background, 0, 0);
    this.addChild(this.bg);

    //Obstacles
    this.pipes = [];
    for (var j = 0; j < 3; j++) {
        var topPipe = new Kiwi.GameObjects.Sprite(this, this.textures.pipe, j * this.pipeDistance + 400 + this.game.stage.width, -Math.random() * 300 - 400);
        this.addChild(topPipe);
        topPipe.transform.rotation += Math.PI;
        this.pipes.push(topPipe);

        var bottomPipe = new Kiwi.GameObjects.Sprite(this, this.textures.pipe, j * this.pipeDistance + 400 + this.game.stage.width, topPipe.transform.y + topPipe.height + this.pipeGap);
        this.addChild(bottomPipe);
        bottomPipe.passed = false;
        bottomPipe.myTop = topPipe;
        this.pipes.push(bottomPipe);
    }

    //Scrolling floor
    this.tileWidth = 37;
    this.tiles = [];
    var tileCount = Math.ceil(this.game.stage.width / this.tileWidth);
    for (var i = 0; i <= tileCount; i++) {
        var t = new Kiwi.GameObjects.Sprite(this, this.textures.ground, i * this.tileWidth, this.game.stage.height - 128);
        this.addChild(t);
        this.tiles.push(t);
    }

    //Flapper
    this.bird = new Kiwi.GameObjects.Sprite(this, this.textures.bird, this.startX, this.startY);
    this.bird.animation.add('flap', [0, 1, 2], 0.1, true);
    this.bird.animation.play('flap');
    this.addChild(this.bird);

    this.birdWidth = this.bird.width;
    this.birdHeight = this.bird.height;

    //Input event for the flapper
    this.game.input.onDown.add(this.flap, this);

    //create, then hide buttons
    this.buttonX = this.game.stage.width / 2 - 107
    this.restartBtn = new Kiwi.GameObjects.Sprite(this, this.textures.restart, -217, this.game.stage.height / 2 - 150, true);
    this.addChild(this.restartBtn);
    this.restartBtn.input.onDown.add(this.restartGame, this);

    this.shareBtn = new Kiwi.GameObjects.Sprite(this, this.textures.share, -217, this.game.stage.height / 2 - 50, true);
    this.addChild(this.shareBtn);
    this.shareBtn.input.onDown.add(this.shareGame, this);

    //Score
    this.score = 0;
    this.scoreText = new Kiwi.GameObjects.Textfield(this, '0', 50, 50, '#FFF');
    this.addChild(this.scoreText);
}

/**
* This method is executed when the player resets the game.
* @method restartGame
* @public
*/
PlayState.restartGame = function () {
    this.gameStarted = false;
    this.gameEnded = false;
    this.score = 0;
    this.scoreText.text = this.score;

    for (var p in this.pipes) {
        var pipe = this.pipes[p];
        pipe.transform.x += 400 + this.game.stage.width;
        if (pipe.transform.rotation == 0) pipe.passed = false;
    }

    this.bird.transform.x = this.startX;
    this.bird.transform.y = this.startY;
    this.bird.transform.rotation = 0;

    this.restartBtn.transform.x = -217;
    this.shareBtn.transform.x = -217;
}

/**
* This method is executed when the user presses the share game button.
* @method shareGame
* @public
*/
PlayState.shareGame = function () {
    //Custom code relating to how you want to 'share' the game will need to go here.
    //Right now we are just going to redirect the user to kiwi.js.org :P
    window.open('https://twitter.com/intent/tweet?original_referer=http%3A%2F%2Ftheoria24.github.io%2FFlappyMiyu%2F&ref_src=twsrc%5Etfw&text=%E7%B5%90%E6%9E%9C%E3%81%AF' + this.score + '%E5%9B%9E%EF%BC%81%0D%0A%0D%0AFlappy+Miyu&tw_p=tweetbutton&url=http%3A%2F%2Ftheoria24.github.io%2FFlappyMiyu%2F');
}

/**
* This method is executed when the user clicks.
* @method flap
* @public
*/
PlayState.flap = function () {
    this.gameStarted = true;
    this.ySpeed = this.flapSpeed;
}

/**
* This method is the main update loop. Move scrolling items here
* @method update
* @public
*/
PlayState.update = function () {
    Kiwi.State.prototype.update.call(this);
    if (this.gameStarted) {
        //update bird y speed and check collisions
        if (this.bird.transform.y < this.game.stage.height) {
            this.bird.transform.y += this.ySpeed;
            if (this.ySpeed < this.maxYSpeed) this.ySpeed += this.gravity;
            if (this.bird.transform.y < 0) this.bird.transform.y = 0;
            if (this.bird.transform.y > 704){
                this.killBird();
                return;
            }
        }
        //update bird rotation based on speed (in radians)
        if (this.ySpeed > 14) {
            this.bird.transform.rotation = Math.PI / 2;
        } else if (this.ySpeed > 6) {
            this.bird.transform.rotation = Math.PI / 6;
        } else {
            this.bird.transform.rotation = -Math.PI / 6;
        }
    }

    //move tiles
    if (!this.gameEnded) {
        for (var t in this.tiles) {
            var tile = this.tiles[t];
            tile.transform.x -= this.xSpeed;
            if (tile.transform.x <= -this.tileWidth) tile.transform.x += this.tileWidth * this.tiles.length;
        }
        if (this.gameStarted) {
            //move pipes
            for (var p in this.pipes) {
                var pipe = this.pipes[p];
                pipe.transform.x -= this.xSpeed;
                if (pipe.transform.rotation == 0) {
                    if (pipe.transform.x < -pipe.width) {
                        pipe.transform.x += this.pipeDistance * 3;
                        pipe.passed = false;
                        pipe.myTop.transform.x = pipe.transform.x;
                        var rand = -Math.random() * 300 - 400;
                        pipe.myTop.transform.y = rand;
                        pipe.transform.y = pipe.myTop.transform.y + pipe.myTop.height + this.pipeGap;
                    }

                    if (pipe.transform.x < this.bird.transform.x && !pipe.passed) {
                        this.score++;
                        this.scoreText.text = this.score;
                        console.log('score:', this.score);
                        pipe.passed = true;
                    }
                }

                if (this.checkCollision(pipe)) {
                    this.killBird();
                    return;
                }
            }
        }
    }
}

/**
* This method checks to see if the bird is colliding with a given pipe.
* @method checkCollision
* @public
* @param pipe{Sprite} The pipe to check colliding with the bird.
*/
PlayState.checkCollision = function (pipe) {
    if (this.bird.transform.x + this.birdWidth > pipe.transform.x) {
        if (this.bird.transform.x < pipe.transform.x + pipe.width) {
            if (this.bird.transform.y + this.birdHeight > pipe.transform.y) {
                if (this.bird.transform.y < pipe.transform.y + pipe.height) {
                    return true;
                }
            }
        }
    }
    return false;
}

/**
* This method is executed when the bird collides with a pipe.
* @method killBird
* @public
*/
PlayState.killBird = function () {
    if (this.gameEnded) return;

    this.gameEnded = true;

    this.shareBtn.transform.x = this.buttonX;
    this.restartBtn.transform.x = this.buttonX;
}
<commit_msg>update<commit_after>var PlayState = new Kiwi.State('PlayState');

/**
* The PlayState in the core state that is used in the game.
*
* It is the state where majority of the functionality occurs 'in-game' occurs.
*
*
* @class playState
* @extends State
* @constructor
*/

/**
* This create method is executed when Kiwi Game reaches the boot stage of the game loop.
* @method create
* @public
*/
PlayState.create = function () {

    //Switch the background colour back to white from purple
    this.game.stage.color = 'ffffff';

    //Variables relating to the state of the game
    this.gameStarted = false;
    this.gameEnded = false;

    //Values pertaining to physics based logic
    this.gravity = 1;
    this.xSpeed = 3;
    this.ySpeed = 0;
    this.maxYSpeed = 16;

    this.flapSpeed = -16;
    this.pipeDistance = 400;
    this.pipeGap = 260;

    //The starting coordinates of the bird.
    this.startX = (this.game.stage.width / 2) - 46
    this.startY = (this.game.stage.height / 2) - 64;

    //Background image
    this.bg = new Kiwi.GameObjects.Sprite(this, this.textures.background, 0, 0);
    this.addChild(this.bg);

    //Obstacles
    this.pipes = [];
    for (var j = 0; j < 3; j++) {
        var topPipe = new Kiwi.GameObjects.Sprite(this, this.textures.pipe, j * this.pipeDistance + 400 + this.game.stage.width, -Math.random() * 300 - 400);
        this.addChild(topPipe);
        topPipe.transform.rotation += Math.PI;
        this.pipes.push(topPipe);

        var bottomPipe = new Kiwi.GameObjects.Sprite(this, this.textures.pipe, j * this.pipeDistance + 400 + this.game.stage.width, topPipe.transform.y + topPipe.height + this.pipeGap);
        this.addChild(bottomPipe);
        bottomPipe.passed = false;
        bottomPipe.myTop = topPipe;
        this.pipes.push(bottomPipe);
    }

    //Scrolling floor
    this.tileWidth = 37;
    this.tiles = [];
    var tileCount = Math.ceil(this.game.stage.width / this.tileWidth);
    for (var i = 0; i <= tileCount; i++) {
        var t = new Kiwi.GameObjects.Sprite(this, this.textures.ground, i * this.tileWidth, this.game.stage.height - 128);
        this.addChild(t);
        this.tiles.push(t);
    }

    //Flapper
    this.bird = new Kiwi.GameObjects.Sprite(this, this.textures.bird, this.startX, this.startY);
    this.bird.animation.add('flap', [0, 1, 2], 0.1, true);
    this.bird.animation.play('flap');
    this.addChild(this.bird);

    this.birdWidth = this.bird.width;
    this.birdHeight = this.bird.height;

    //Input event for the flapper
    this.game.input.onDown.add(this.flap, this);

    //create, then hide buttons
    this.buttonX = this.game.stage.width / 2 - 107
    this.restartBtn = new Kiwi.GameObjects.Sprite(this, this.textures.restart, -217, this.game.stage.height / 2 - 150, true);
    this.addChild(this.restartBtn);
    this.restartBtn.input.onDown.add(this.restartGame, this);

    this.shareBtn = new Kiwi.GameObjects.Sprite(this, this.textures.share, -217, this.game.stage.height / 2 - 50, true);
    this.addChild(this.shareBtn);
    this.shareBtn.input.onDown.add(this.shareGame, this);

    //Score
    this.score = 0;
    this.scoreText = new Kiwi.GameObjects.Textfield(this, '0', 50, 50, '#FFF');
    this.addChild(this.scoreText);
}

/**
* This method is executed when the player resets the game.
* @method restartGame
* @public
*/
PlayState.restartGame = function () {
    this.gameStarted = false;
    this.gameEnded = false;
    this.score = 0;
    this.scoreText.text = this.score;

    for (var p in this.pipes) {
        var pipe = this.pipes[p];
        pipe.transform.x += 400 + this.game.stage.width;
        if (pipe.transform.rotation == 0) pipe.passed = false;
    }

    this.bird.transform.x = this.startX;
    this.bird.transform.y = this.startY;
    this.bird.transform.rotation = 0;

    this.restartBtn.transform.x = -217;
    this.shareBtn.transform.x = -217;
}

/**
* This method is executed when the user presses the share game button.
* @method shareGame
* @public
*/
PlayState.shareGame = function () {
    //Custom code relating to how you want to 'share' the game will need to go here.
    //Right now we are just going to redirect the user to kiwi.js.org :P
    window.open('https://twitter.com/intent/tweet?original_referer=http%3A%2F%2Ftheoria24.github.io%2FFlappyMiyu%2F&ref_src=twsrc%5Etfw&text=%E7%B5%90%E6%9E%9C%E3%81%AF%E5%9B%9E%EF%BC%81%0D%0A%0D%0AFlappy+Miyu&tw_p=tweetbutton&url=http%3A%2F%2Ftheoria24.github.io%2FFlappyMiyu%2F');
}

/**
* This method is executed when the user clicks.
* @method flap
* @public
*/
PlayState.flap = function () {
    this.gameStarted = true;
    this.ySpeed = this.flapSpeed;
}

/**
* This method is the main update loop. Move scrolling items here
* @method update
* @public
*/
PlayState.update = function () {
    Kiwi.State.prototype.update.call(this);
    if (this.gameStarted) {
        //update bird y speed and check collisions
        if (this.bird.transform.y < this.game.stage.height) {
            this.bird.transform.y += this.ySpeed;
            if (this.ySpeed < this.maxYSpeed) this.ySpeed += this.gravity;
            if (this.bird.transform.y < 0) this.bird.transform.y = 0;
            if (this.bird.transform.y > 704){
                this.killBird();
                return;
            }
        }
        //update bird rotation based on speed (in radians)
        if (this.ySpeed > 14) {
            this.bird.transform.rotation = Math.PI / 2;
        } else if (this.ySpeed > 6) {
            this.bird.transform.rotation = Math.PI / 6;
        } else {
            this.bird.transform.rotation = -Math.PI / 6;
        }
    }

    //move tiles
    if (!this.gameEnded) {
        for (var t in this.tiles) {
            var tile = this.tiles[t];
            tile.transform.x -= this.xSpeed;
            if (tile.transform.x <= -this.tileWidth) tile.transform.x += this.tileWidth * this.tiles.length;
        }
        if (this.gameStarted) {
            //move pipes
            for (var p in this.pipes) {
                var pipe = this.pipes[p];
                pipe.transform.x -= this.xSpeed;
                if (pipe.transform.rotation == 0) {
                    if (pipe.transform.x < -pipe.width) {
                        pipe.transform.x += this.pipeDistance * 3;
                        pipe.passed = false;
                        pipe.myTop.transform.x = pipe.transform.x;
                        var rand = -Math.random() * 300 - 400;
                        pipe.myTop.transform.y = rand;
                        pipe.transform.y = pipe.myTop.transform.y + pipe.myTop.height + this.pipeGap;
                    }

                    if (pipe.transform.x < this.bird.transform.x && !pipe.passed) {
                        this.score++;
                        this.scoreText.text = this.score;
                        console.log('score:', this.score);
                        pipe.passed = true;
                    }
                }

                if (this.checkCollision(pipe)) {
                    this.killBird();
                    return;
                }
            }
        }
    }
}

/**
* This method checks to see if the bird is colliding with a given pipe.
* @method checkCollision
* @public
* @param pipe{Sprite} The pipe to check colliding with the bird.
*/
PlayState.checkCollision = function (pipe) {
    if (this.bird.transform.x + this.birdWidth > pipe.transform.x) {
        if (this.bird.transform.x < pipe.transform.x + pipe.width) {
            if (this.bird.transform.y + this.birdHeight > pipe.transform.y) {
                if (this.bird.transform.y < pipe.transform.y + pipe.height) {
                    return true;
                }
            }
        }
    }
    return false;
}

/**
* This method is executed when the bird collides with a pipe.
* @method killBird
* @public
*/
PlayState.killBird = function () {
    if (this.gameEnded) return;

    this.gameEnded = true;

    this.shareBtn.transform.x = this.buttonX;
    this.restartBtn.transform.x = this.buttonX;
}
<|endoftext|>


<commit_before>/*
 *  Copyright 2015 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

module.exports = (function() {
  var path = require('path');
  var ReadLine = require('readline');
  var spawn = require('child_process').spawn;
  var events = require('events');
  var os = require('os');
  var request = require('request');

  var _url;
  var _hash;
  var _local;
  var _backend;
  var _running = false;

  var _osName = os.type();

  return {
    startNew: function() {
      var eventEmitter = new events.EventEmitter();

      if (_osName.startsWith('Windows')) {
        process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jdk');
        process.chdir(__dirname + '/../dist');
        _backend = spawn(path.resolve(__dirname + '/../dist/beaker.command.bat'), ['--open-browser', 'false']);
      } else if (_osName.startsWith('Darwin')) {
        process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jdk/Contents/Home');
        _backend = spawn(path.resolve(__dirname + '/../dist/beaker.command'), ['--open-browser', 'false']);
      } else if (_osName.startsWith('Linux')) {
        process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jdk');
        _backend = spawn(path.resolve(__dirname + '/../dist/beaker.command'), ['--open-browser', 'false']);
      }

      var rl = ReadLine.createInterface({
        input: _backend.stdout
      });

      rl.on('line', function(line) {
        console.log(line); // Pipe backend's stdout to electron's stdout
        if (line.startsWith('Beaker hash')) {
          _hash = line.split(' ')[2];
        } else if (line.startsWith('Beaker listening on')) {
          _url = line.split(' ')[3];
          _local = true;
          _running = true;
          eventEmitter.emit('ready', {
            url: _url,
            hash: _hash,
            local: _local
          });
        }
      });
      return eventEmitter;
    },
    kill: function() {
      var eventEmitter = new events.EventEmitter();
      if (_local) {
        request(this.getUrl() + this.getHash() + '/beaker/rest/util/exit', function (error, response, body) {
          _running = false;
          eventEmitter.emit('killed');
        });
      }
      _backend = {};
      return eventEmitter;
    },
    getInfo: function() {
      return {
        url: _url,
        hash: _hash,
        local: _local,
        running: _running
      };
    },
    getUrl: function() {
      return _url;
    },
    setUrl: function(url) {
      _url = url;
    },
    getHash: function() {
      return _hash;
    },
    setHash: function(hash) {
      _hash = hash;
    },
    getLocal: function() {
      return _local;
    },
    setLocal: function(local) {
      _local = local;
    },
    isRunning: function() {
      return _running;
    }
  }
})();
<commit_msg>windows electron version leaks processes #3982<commit_after>/*
 *  Copyright 2015 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

module.exports = (function() {
  var path = require('path');
  var ReadLine = require('readline');
  var spawn = require('child_process').spawn;
  var events = require('events');
  var os = require('os');
  var request = require('request');
  const session = require('electron').session;

  var _url;
  var _hash;
  var _local;
  var _backend;
  var _running = false;

  var _osName = os.type();

  return {
    startNew: function() {
      var eventEmitter = new events.EventEmitter();

      if (_osName.startsWith('Windows')) {
        process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jdk');
        process.chdir(__dirname + '/../dist');
        _backend = spawn(path.resolve(__dirname + '/../dist/beaker.command.bat'), ['--open-browser', 'false']);
      } else if (_osName.startsWith('Darwin')) {
        process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jdk/Contents/Home');
        _backend = spawn(path.resolve(__dirname + '/../dist/beaker.command'), ['--open-browser', 'false']);
      } else if (_osName.startsWith('Linux')) {
        process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jdk');
        _backend = spawn(path.resolve(__dirname + '/../dist/beaker.command'), ['--open-browser', 'false']);
      }

      var rl = ReadLine.createInterface({
        input: _backend.stdout
      });

      rl.on('line', function(line) {
        console.log(line); // Pipe backend's stdout to electron's stdout
        if (line.startsWith('Beaker hash')) {
          _hash = line.split(' ')[2];
        } else if (line.startsWith('Beaker listening on')) {
          _url = line.split(' ')[3];
          _local = true;
          _running = true;
          eventEmitter.emit('ready', {
            url: _url,
            hash: _hash,
            local: _local
          });
        }
      });
      return eventEmitter;
    },
    kill: function() {
      var eventEmitter = new events.EventEmitter();
      if (_local) {
        var self = this;
        session.defaultSession.cookies.get({name : "XSRF-TOKEN"}, function(error, cookies) {
          var options = {
            url: self.getUrl() + self.getHash() + '/beaker/rest/util/exit',
            headers: {
              'X-XSRF-TOKEN': cookies[0].value
            }
          };
          function callback(error, response, body) {
            _running = false;
            eventEmitter.emit('killed');
          }
          request(options, callback);
        });
      }
      _backend = {};
      return eventEmitter;
    },
    getInfo: function() {
      return {
        url: _url,
        hash: _hash,
        local: _local,
        running: _running
      };
    },
    getUrl: function() {
      return _url;
    },
    setUrl: function(url) {
      _url = url;
    },
    getHash: function() {
      return _hash;
    },
    setHash: function(hash) {
      _hash = hash;
    },
    getLocal: function() {
      return _local;
    },
    setLocal: function(local) {
      _local = local;
    },
    isRunning: function() {
      return _running;
    }
  }
})();
<|endoftext|>


<commit_before>var context = new (window.AudioContext || window.webkitAudioContext)();

$(document).ready(function(){
    $('#start').modal({
        backdrop: 'static',
        keyboard: false
    });
    $('#start').modal('show');
    $('#green').click(function(){
        selectColor('green');
        checkLoss('green');
    });
    $('#red').click(function(){
        selectColor('red');
        checkLoss('red');
    });
    $('#yellow').click(function(){
        selectColor('yellow');
        checkLoss('yellow');
    });
    $('#blue').click(function(){
        selectColor('blue');
        checkLoss('blue');
    });
});

var wins = 0; //number of wins
var plays = 0; //number of plays
var interval; //interval for pattern display
var count = 0; //counter for pattern display
var pattern = []; //array to hold pattern
var position; //position for checkLoss
var clickable = false;

function startGame(){
    //$('#start').hide();
    game();
}

function game(){
    clickable = false;
    position = 0;
    plays+=1;
    playPattern();
}

function checkLoss(color){
    if(!clickable){
        return;
    }
    if(pattern[position]==color){
        position++;
        if(position == pattern.length){
            wins++;
            game();
        }
    }
    else{
        endGame();
    }
}

function endGame(){
    var s = 'Score: '+wins;
    $('#score').text(s);
    $('#end').modal('show');
}

function playPattern(){
    colors = ['green','red','yellow','blue'];
    colorIndex = Math.floor(Math.random()*4);
    pattern.push(colors[colorIndex]);
    count = pattern.length;
    interval = setInterval(patternHelper, 1000, pattern);
}

function patternHelper(pattern){
    selectColor(pattern[pattern.length-count]);
    if(count>0){
        count--;
    }
    else{
        clearInterval(interval);
        $('#play').modal('show');
        setTimeout(function(){
            $('#play').modal('hide');
            clickable = true;
        },1500);
    }
}

function selectColor(color){
    if(color == 'green'){
        $('#green').css('background-color', 'lightgreen');
        var osc1 = context.createOscillator(); // instantiate an oscillator
        osc1.type = 'square'; // this is the default - also square, sawtooth, triangle
        osc1.frequency.value = 329.63; // Hz
        osc1.connect(context.destination); // connect it to the destination
        osc1.start(); // start the oscillator
        osc1.stop(context.currentTime + .3); // stop 2 seconds after the current time
    }
    else if(color == 'red'){
        $('#red').css('background-color', 'pink');
        var osc2 = context.createOscillator(); // instantiate an oscillator
        osc2.type = 'square'; // this is the default - also square, sawtooth, triangle
        osc2.frequency.value = 220; // Hz
        osc2.connect(context.destination); // connect it to the destination
        osc2.start(); // start the oscillator
        osc2.stop(context.currentTime + .3); // stop 2 seconds after the current time

    }
    else if(color == 'yellow'){
        $('#yellow').css('background-color', 'lightyellow');
        var osc3 = context.createOscillator(); // instantiate an oscillator
        osc3.type = 'square'; // this is the default - also square, sawtooth, triangle
        osc3.frequency.value = 277.18; // Hz
        osc3.connect(context.destination); // connect it to the destination
        osc3.start(); // start the oscillator
        osc3.stop(context.currentTime + .3); // stop 2 seconds after the current time
    }
    else if(color == 'blue'){
        $('#blue').css('background-color', 'lightblue');
        var osc4 = context.createOscillator(); // instantiate an oscillator
        osc4.type = 'square'; // this is the default - also square, sawtooth, triangle
        osc4.frequency.value = 164.81; // Hz
        osc4.connect(context.destination); // connect it to the destination
        osc4.start(); // start the oscillator
        osc4.stop(context.currentTime + .3); // stop 2 seconds after the current time
    }
    setTimeout(resetColor, 500); //make less dependent on timing
}

function resetColor(){
    $('div').css('background-color','');
}
<commit_msg>Push to Github<commit_after>var context = new (window.AudioContext || window.webkitAudioContext)();

$(document).ready(function(){
    $('#start').modal({
        backdrop: 'static',
        keyboard: false
    });
    $('#start').modal('show');
    $('#green').click(function(){
        selectColor('green');
        checkLoss('green');
    });
    $('#red').click(function(){
        selectColor('red');
        checkLoss('red');
    });
    $('#yellow').click(function(){
        selectColor('yellow');
        checkLoss('yellow');
    });
    $('#blue').click(function(){
        selectColor('blue');
        checkLoss('blue');
    });
});

var wins = 0; //number of wins
var plays = 0; //number of plays
var interval; //interval for pattern display
var count = 0; //counter for pattern display
var pattern = []; //array to hold pattern
var position; //position for checkLoss
var clickable = false;

function startGame(){
    //$('#start').hide();
    game();
}

function game(){
    clickable = false;
    position = 0;
    plays+=1;
    playPattern();
}

function checkLoss(color){
    if(!clickable){
        return;
    }
    if(pattern[position]==color){
        position++;
        if(position == pattern.length){
            wins++;
            game();
        }
    }
    else{
        endGame();
    }
}

function endGame(){
    var s = 'Score: '+wins;
    $('#score').text(s);
    $('#end').modal('show');
}

function playPattern(){
    colors = ['green','red','yellow','blue'];
    colorIndex = Math.floor(Math.random()*4);
    pattern.push(colors[colorIndex]);
    count = pattern.length;
    interval = setInterval(patternHelper, 1000, pattern);
}

function patternHelper(pattern){
    selectColor(pattern[pattern.length-count]);
    if(count>0){
        count--;
    }
    else{
        clearInterval(interval);
        $('#play').modal('show');
        setTimeout(function(){
            $('#play').modal('hide');
            clickable = true;
        },1500);
    }
}

function selectColor(color){
    if(color == 'green'){
        $('#green').css('background-color', 'lightgreen');
        var osc1 = context.createOscillator(); // instantiate an oscillator
        osc1.type = 'square'; // this is the default - also square, sawtooth, triangle
        osc1.frequency.value = 329.63; // Hz
        osc1.connect(context.destination); // connect it to the destination
        osc1.start(); // start the oscillator
        osc1.stop(context.currentTime + .3); // stop 2 seconds after the current time
    }
    else if(color == 'red'){
        $('#red').css('background-color', 'pink');
        var osc2 = context.createOscillator(); // instantiate an oscillator
        osc2.type = 'square'; // this is the default - also square, sawtooth, triangle
        osc2.frequency.value = 220; // Hz
        osc2.connect(context.destination); // connect it to the destination
        osc2.start(); // start the oscillator
        osc2.stop(context.currentTime + .3); // stop 2 seconds after the current time

    }
    else if(color == 'yellow'){
        $('#yellow').css('background-color', 'lightyellow');
        var osc3 = context.createOscillator(); // instantiate an oscillator
        osc3.type = 'square'; // this is the default - also square, sawtooth, triangle
        osc3.frequency.value = 277.18; // Hz
        osc3.connect(context.destination); // connect it to the destination
        osc3.start(); // start the oscillator
        osc3.stop(context.currentTime + .3); // stop 2 seconds after the current time
    }
    else if(color == 'blue'){
        $('#blue').css('background-color', 'lightblue');
        var osc4 = context.createOscillator(); // instantiate an oscillator
        osc4.type = 'square'; // this is the default - also square, sawtooth, triangle
        osc4.frequency.value = 164.81; // Hz
        osc4.connect(context.destination); // connect it to the destination
        osc4.start(); // start the oscillator
        osc4.stop(context.currentTime + .3); // stop 2 seconds after the current time
    }
    setTimeout(resetColor, 500); //make less dependent on timing
}

function resetColor(){
    $('div').css('background-color','');
}
<|endoftext|>


<commit_before>
/**
 * Created by Nguyen on 4/29/2015.
 */
(function () {
    'use strict';
    var app, deps;

    deps = ['treeTable'];

    app = angular.module('treeTableTest', deps);
    app.controller(
        'CategoryMenuController', [
            '$scope', '$TreeTableConvert', 'DataDemo', function ($scope, $TreeTableConvert, DataDemo) {
                // debug in demo
                $scope.branch = {};
                $scope.log = {};

                var tree;
                $scope.tree_data = {};
                $scope.my_tree = tree = {};

                // set callbacks to tree-table
                $scope.callbacks = {
                    accept: function (source, dest, index_dest) {
                        return true;
                    }
                }

                $scope.my_tree.addFunction = function (b) {
                    console.log(b);
                    alert('Function added in Controller "App.js"');
                }

                $scope.remove_branch = function () {
                    return $scope.my_tree.remove_branch();
                }

                $scope.my_tree_handler = function (branch) {
                    console.log('you clicked on', branch)
                }

                $scope.expanding_property = {
                    /*template: "OK All	",*/
                    field:       "Name",
                    titleClass:  'text-center',
                    cellClass:   'v-middle',
                    displayName: 'Name'
                };
                $scope.col_defs = [
                    {
                        field: "Description"
                    }, {
                        field: "Area"
                    }, {
                        field: "Population"
                    }, {
                        field:       "TimeZone",
                        displayName: "Time Zone"
                    }, {
                        field:        "Description",
                        titleStyle:   {
                            'width': '80pt'
                        },
                        titleClass:   'text-center',
                        cellClass:    'v-middle text-center',
                        displayName:  'Description',
                        cellTemplate: ""
                    }, {
                        displayName:  'Function',
                        cellTemplate: '<button ng-click="tree.addFunction(row)" class="btn btn-default btn-sm">Added Controller!</button>'
                    }, {
                        displayName:  'Remove',
                        cellTemplate: '<button ng-click="tree.remove_branch(row)" class="btn btn-default btn-sm">Remove</button>'
                    }];
                $scope.tree_data = $TreeTableConvert.line2tree(DataDemo.getDatas(), 'DemographicId', 'ParentId');
            }]
    ).factory(
        'DataDemo', function () {
            return {
                getDatas: function () {
                    return [
                        {
                            "DemographicId": 1,
                            "ParentId":      null,
                            "Name":          "United States of America",
                            "Description":   "United States of America",
                            "Area":          9826675,
                            "Population":    318212000,
                            "TimeZone":      "UTC -5 to -10"
                        }, {
                            "DemographicId": 2,
                            "ParentId":      1,
                            "Name":          "California",
                            "Description":   "The Tech State",
                            "Area":          423970,
                            "Population":    38340000,
                            "TimeZone":      "Pacific Time"
                        }, {
                            "DemographicId": 3,
                            "ParentId":      2,
                            "Name":          "San Francisco",
                            "Description":   "The happening city",
                            "Area":          231,
                            "Population":    837442,
                            "TimeZone":      "PST"
                        }, {
                            "DemographicId": 4,
                            "ParentId":      2,
                            "Name":          "Los Angeles",
                            "Description":   "Disco city",
                            "Area":          503,
                            "Population":    3904657,
                            "TimeZone":      "PST"
                        }, {
                            "DemographicId": 5,
                            "ParentId":      1,
                            "Name":          "Illinois",
                            "Description":   "Not so cool",
                            "Area":          57914,
                            "Population":    12882135,
                            "TimeZone":      "Central Time Zone"
                        }, {
                            "DemographicId": 6,
                            "ParentId":      5,
                            "Name":          "Chicago",
                            "Description":   "Financial City",
                            "Area":          234,
                            "Population":    2695598,
                            "TimeZone":      "CST"
                        }, {
                            "DemographicId": 7,
                            "ParentId":      1,
                            "Name":          "Texas",
                            "Description":   "Rances, Oil & Gas",
                            "Area":          268581,
                            "Population":    26448193,
                            "TimeZone":      "Mountain"
                        }, {
                            "DemographicId": 8,
                            "ParentId":      1,
                            "Name":          "New York",
                            "Description":   "The largest diverse city",
                            "Area":          141300,
                            "Population":    19651127,
                            "TimeZone":      "Eastern Time Zone"
                        }, {
                            "DemographicId": 14,
                            "ParentId":      8,
                            "Name":          "Manhattan",
                            "Description":   "Time Square is the place",
                            "Area":          269.403,
                            "Population":    0,
                            "TimeZone":      "EST"
                        }, {
                            "DemographicId": 15,
                            "ParentId":      14,
                            "Name":          "Manhattan City",
                            "Description":   "Manhattan island",
                            "Area":          33.77,
                            "Population":    0,
                            "TimeZone":      "EST"
                        }, {
                            "DemographicId": 16,
                            "ParentId":      14,
                            "Name":          "Time Square",
                            "Description":   "Time Square for new year",
                            "Area":          269.40,
                            "Population":    0,
                            "TimeZone":      "EST"
                        }, {
                            "DemographicId": 17,
                            "ParentId":      8,
                            "Name":          "Niagra water fall",
                            "Description":   "Close to Canada",
                            "Area":          65.7,
                            "Population":    0,
                            "TimeZone":      "EST"
                        }, {
                            "DemographicId": 18,
                            "ParentId":      8,
                            "Name":          "Long Island",
                            "Description":   "Harbour to Atlantic",
                            "Area":          362.9,
                            "Population":    0,
                            "TimeZone":      "EST"
                        }, {
                            "DemographicId": 51,
                            "ParentId":      1,
                            "Name":          "All_Other",
                            "Description":   "All_Other demographics",
                            "Area":          0,
                            "Population":    0,
                            "TimeZone":      0
                        }, {
                            "DemographicId": 201,
                            "ParentId":      null,
                            "Name":          "India",
                            "Description":   "Hydrabad tech city",
                            "Area":          9826675,
                            "Population":    318212000,
                            "TimeZone":      "IST"
                        }, {
                            "DemographicId": 301,
                            "ParentId":      null,
                            "Name":          "Bangladesh",
                            "Description":   "Country of love",
                            "Area":          9826675,
                            "Population":    318212000,
                            "TimeZone":      "BST"
                        }];
                }
            }
        }
    );
})();
<commit_msg>Fix Demo<commit_after>/**
 * Created by Nguyen on 4/29/2015.
 */
/**
 * Created by Nguyen on 4/29/2015.
 */
(function () {
    'use strict';
    var app, deps;

    deps = ['treeTable'];

    app = angular.module('treeTableTest', deps);
    app.controller(
        'CategoryMenuController', [
            '$scope', '$TreeTableConvert', 'DataDemo', function ($scope, $TreeTableConvert, DataDemo) {
                // debug in demo
                $scope.branch = {};
                $scope.log = {};

                var tree;
                $scope.tree_data = {};
                $scope.my_tree = tree = {};

                // set callbacks to tree-table
                $scope.callbacks = {
                    accept: function (source, dest, index_dest) {
                        return true;
                    }
                }

                $scope.my_tree.addFunction = function (b) {
                    console.log(b);
                    alert('Function added in Controller "App.js"');
                }

                $scope.remove_branch = function () {
                    return $scope.my_tree.remove_branch();
                }

                $scope.my_tree_handler = function (branch) {
                    console.log('you clicked on', branch)
                }

                $scope.expanding_property = {
                    /*template: "OK All	",*/
                    field:       "Name",
                    titleClass:  'text-center',
                    cellClass:   'v-middle',
                    displayName: 'Name'
                };
                $scope.col_defs = [
                    {
                        field: "Description"
                    }, {
                        field:        "Description",
                        titleStyle:   {
                            'width': '80pt'
                        },
                        titleClass:   'text-center',
                        cellClass:    'v-middle text-center',
                        displayName:  'Description',
                        cellTemplate: ""
                    }, {
                        displayName:  'Function',
                        cellTemplate: '<button ng-click="tree.addFunction(row)" class="btn btn-default btn-sm">Added Controller!</button>'
                    }, {
                        displayName:  'Remove',
                        cellTemplate: '<button ng-click="tree.remove_branch(row)" class="btn btn-default btn-sm">Remove</button>'
                    }];
                $scope.tree_data = $TreeTableConvert.line2tree(DataDemo.getDatas(), 'DemographicId', 'ParentId');
            }]
    ).factory(
        'DataDemo', function () {
            return {
                getDatas: function () {
                    return [
                        {
                            "DemographicId": 1,
                            "ParentId":      null,
                            "Name":          "United States of America",
                            "Description":   "United States of America",
                            "Area":          9826675,
                            "Population":    318212000,
                            "TimeZone":      "UTC -5 to -10"
                        }, {
                            "DemographicId": 2,
                            "ParentId":      1,
                            "Name":          "California",
                            "Description":   "The Tech State",
                            "Area":          423970,
                            "Population":    38340000,
                            "TimeZone":      "Pacific Time"
                        }, {
                            "DemographicId": 3,
                            "ParentId":      2,
                            "Name":          "San Francisco",
                            "Description":   "The happening city",
                            "Area":          231,
                            "Population":    837442,
                            "TimeZone":      "PST"
                        }, {
                            "DemographicId": 4,
                            "ParentId":      2,
                            "Name":          "Los Angeles",
                            "Description":   "Disco city",
                            "Area":          503,
                            "Population":    3904657,
                            "TimeZone":      "PST"
                        }, {
                            "DemographicId": 5,
                            "ParentId":      1,
                            "Name":          "Illinois",
                            "Description":   "Not so cool",
                            "Area":          57914,
                            "Population":    12882135,
                            "TimeZone":      "Central Time Zone"
                        }, {
                            "DemographicId": 6,
                            "ParentId":      5,
                            "Name":          "Chicago",
                            "Description":   "Financial City",
                            "Area":          234,
                            "Population":    2695598,
                            "TimeZone":      "CST"
                        }, {
                            "DemographicId": 7,
                            "ParentId":      1,
                            "Name":          "Texas",
                            "Description":   "Rances, Oil & Gas",
                            "Area":          268581,
                            "Population":    26448193,
                            "TimeZone":      "Mountain"
                        }, {
                            "DemographicId": 8,
                            "ParentId":      1,
                            "Name":          "New York",
                            "Description":   "The largest diverse city",
                            "Area":          141300,
                            "Population":    19651127,
                            "TimeZone":      "Eastern Time Zone"
                        }, {
                            "DemographicId": 14,
                            "ParentId":      8,
                            "Name":          "Manhattan",
                            "Description":   "Time Square is the place",
                            "Area":          269.403,
                            "Population":    0,
                            "TimeZone":      "EST"
                        }, {
                            "DemographicId": 15,
                            "ParentId":      14,
                            "Name":          "Manhattan City",
                            "Description":   "Manhattan island",
                            "Area":          33.77,
                            "Population":    0,
                            "TimeZone":      "EST"
                        }, {
                            "DemographicId": 16,
                            "ParentId":      14,
                            "Name":          "Time Square",
                            "Description":   "Time Square for new year",
                            "Area":          269.40,
                            "Population":    0,
                            "TimeZone":      "EST"
                        }, {
                            "DemographicId": 17,
                            "ParentId":      8,
                            "Name":          "Niagra water fall",
                            "Description":   "Close to Canada",
                            "Area":          65.7,
                            "Population":    0,
                            "TimeZone":      "EST"
                        }, {
                            "DemographicId": 18,
                            "ParentId":      8,
                            "Name":          "Long Island",
                            "Description":   "Harbour to Atlantic",
                            "Area":          362.9,
                            "Population":    0,
                            "TimeZone":      "EST"
                        }, {
                            "DemographicId": 51,
                            "ParentId":      1,
                            "Name":          "All_Other",
                            "Description":   "All_Other demographics",
                            "Area":          0,
                            "Population":    0,
                            "TimeZone":      0
                        }, {
                            "DemographicId": 201,
                            "ParentId":      null,
                            "Name":          "India",
                            "Description":   "Hydrabad tech city",
                            "Area":          9826675,
                            "Population":    318212000,
                            "TimeZone":      "IST"
                        }, {
                            "DemographicId": 301,
                            "ParentId":      null,
                            "Name":          "Bangladesh",
                            "Description":   "Country of love",
                            "Area":          9826675,
                            "Population":    318212000,
                            "TimeZone":      "BST"
                        }];
                }
            }
        }
    );
})();
<|endoftext|>


<commit_before>'use strict';

angular.module('acceptanceTests').controller('LoginCtrl', function($scope, $state, UserService) {
    $scope.submit = function() {
        $scope.waiting = true;
        $scope.badCredentials = false;
        UserService.login($scope.email, $scope.password)
            .then(function() {
                $state.go('index');
            }).catch(function(e) {
                $scope.badCredentials = true;
                $scope.waiting = false;
            });
    };
});
<commit_msg>fix jshint<commit_after>'use strict';

angular.module('acceptanceTests').controller('LoginCtrl', function($scope, $state, UserService) {
    $scope.submit = function() {
        $scope.waiting = true;
        $scope.badCredentials = false;
        UserService.login($scope.email, $scope.password)
            .then(function() {
                $state.go('index');
            }).catch(function() {
                $scope.badCredentials = true;
                $scope.waiting = false;
            });
    };
});
<|endoftext|>


<commit_before>/*
   Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.

   This file is licensed under the Apache License, Version 2.0 (the "License").
   You may not use this file except in compliance with the License. A copy of
   the License is located at

    http://aws.amazon.com/apache2.0/

   This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied. See the License for the
   specific language governing permissions and limitations under the License.

   ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
   https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-managing-identities.html
*/

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'REGION'});

// Create the promise and SES service object
var deletePromise = new AWS.SES({apiVersion: '2010-12-01'}).deleteIdentity({Identity: "DOMAIN_NAME"}).promise();

// Handle promise's fulfilled/rejected states
deletePromise.then(
  function(data) {
    console.log("Identity Deleted");
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });
<commit_msg>Update ses_deleteidentity.js<commit_after>// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND.

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-managing-identities.html
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'REGION'});

// Create the promise and SES service object
var deletePromise = new AWS.SES({apiVersion: '2010-12-01'}).deleteIdentity({Identity: "DOMAIN_NAME"}).promise();

// Handle promise's fulfilled/rejected states
deletePromise.then(
  function(data) {
    console.log("Identity Deleted");
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });
<|endoftext|>


<commit_before>const groupFn = function(fn, label) {
  console.group(label || 'Group-function')
  const ret = fn()
  console.groupEnd()
  return ret
}

class Program {
  constructor() {
    this.functions = {}
    this.labels = {}
    this.defaultAttributes = {
      type: 'c', auto: true, conditional: false
    }
  }

  parseAttributes(str) {
    const timesAppearing = {}
    const validAttributes = [
      'c', 'i', 'r',
      '0', '1',
      '!', '?'
    ]
    const attributes = {}
    let contradictory
    let overallContradictory = 0
    const result = {}

    for (let char of str) {
      timesAppearing[char] = (timesAppearing[char] || 0) + 1
      if (timesAppearing[char] > 1) throw new Error(
        `In attributes "${str}" ${char} appears more than once`)

      if (!validAttributes.includes(char)) throw new Error(
        `In attributes "${str}" ${char} is an invalid attribute`)

      attributes[char] = true
    }

    contradictory = 0
    if (attributes['c']) {
      contradictory++
      result.type = 'c'
    }
    if (attributes['i']) {
      contradictory++
      result.type = 'i'
    }
    if (attributes['r']) {
      contradictory++
      result.type = 'r'
    }
    overallContradictory |= contradictory > 1

    contradictory = 0
    if (attributes['0']) {
      contradictory++
      result.auto = false
    }
    if (attributes['1']) {
      contradictory++
      result.auto = true
    }
    overallContradictory |= contradictory > 1

    contradictory = 0
    if (attributes['?']) {
      result.conditional = true
      contradictory++
    }
    if (attributes['!']) {
      result.conditional = false
      contradictory++
    }
    overallContradictory |= contradictory > 1

    if (overallContradictory) throw new Error(
      `Attributes "${str}" is contradictory`)

    const withDefaults = Object.assign({}, this.defaultAttributes, result)

    return withDefaults
  }

  compile(code, environment = {vars: {}}) {
    const lines = code.split('\n')
    const results = []

    LINE_LOOP:
    for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
      let line = lines[lineIndex]

      if (line === '')
        continue

      if (line.startsWith('define')) {
        // Getting name
        let name = ''

        let defCharIndex = 6
        while (true) {
          defCharIndex++
          const char = line[defCharIndex]

          if (defCharIndex >= line.length)
            break

          if (char === '(')
            break

          name += char
        }

        // Getting parameters
        let params = []
        let currentParam = ''

        while (true) {
          defCharIndex++
          const char = line[defCharIndex]

          if (defCharIndex >= line.length)
            break

          if (char === ')') {
            if (currentParam) {
              params.push(currentParam)
            }
            break
          }

          if (char === ',') {
            params.push(currentParam)
            currentParam = ''
            continue
          }

          if (char === ' ' && currentParam === '')
            continue

          currentParam += char
        }

        // Getting code lines
        const codeLines = []

        while (true) {
          lineIndex++
          line = lines[lineIndex]

          if (lineIndex > lines.length)
            break

          if (!line.startsWith('  '))
            break

          codeLines.push(line.slice(2))
        }

        // Storing function
        this.functions[name] = {codeLines, params}

        continue
      }

      if (line.startsWith('!')) {
        const env = Object.assign({}, environment)

        if (line.endsWith(':')) {
          const argCodeLines = []
          while (true) {
            lineIndex++
            const line = lines[lineIndex]
            if (lineIndex >= lines.length) break
            if (!line.startsWith('  ')) break
            argCodeLines.push(line.slice(2))
          }
          env.passedCode = argCodeLines
        }

        console.log('line:', line)

        const { funcResults, name } = this.processFunctionCall(
          line.slice(1), env)

        if (funcResults.length === 0) {
          console.warn(`Procedure call "${name}" had no results!`)
        }

        for (let r of funcResults) {
          results.push(r)
        }

        continue
      }

      if (line.startsWith('#')) {
        const blockName = line.slice(1)
        results.push({block: blockName})
        continue
      }

      if (line.startsWith('@')) {
        const labelName = line.slice(1)
        this.labels[labelName] = results.length
        continue
      }

      let attributeStr = ''
      let charIndex = -1
      let char = ''
      while (true) {
        charIndex++
        char = line[charIndex]
        if (char === ' ') {
          attributeStr = ''
          break
        }
        if (charIndex >= line.length) {
          attributeStr = ''
          break
        }
        if (char === ':') break
        attributeStr += char
      }

      let commandPart
      if (attributeStr) {
        let char = ''
        do {
          charIndex++
          char = line[charIndex]
        } while (char === ' ')
        commandPart = line.slice(charIndex)
      } else {
        commandPart = line
      }
      const attributes = this.parseAttributes(attributeStr)
      console.log('attributes proper:', attributes)

      const command = this.expression(commandPart, environment)

      const obj = Object.assign({command}, attributes)

      results.push(obj)
    }

    return results
  }

  expression(code, environment = {vars: {}}) {
    // TODO: put reused stuff in here because having identical code in multiple
    // parts of a program is BAAAD!

    // Parts of lines that should be put in here:
    // * everything past the command name part of code lines (past first space)
    //   (or just the whole command line)
    // * arguments (each in a separate expression call)

    let charIndex = -1
    let result = ''

    console.log('EXPRESSION:', code)

    while (true) {
      charIndex++
      let char = code[charIndex]
      if (charIndex >= code.length) break

      // Variables
      if (char === '$') {
        let name = ''
        while (true) {
          charIndex++
          char = code[charIndex]
          if (charIndex >= code.length) break

          if (char === ' ') {
            charIndex--
            break
          }

          name += char
        }

        // console.log('Variable:', name)
        // console.log('Environment:', environment)
        // console.log('Value:', environment.vars[name])

        if (!environment.vars.hasOwnProperty(name))
          throw new Error(`Access to undefined variable: "${name}"`)

        result += environment.vars[name]

        continue
      }

      // Function calls
      if (char === '^') {
        // console.group('fn call')

        const { funcResults, newCharIndex, name } = this.processFunctionCall(
          code.slice(charIndex + 1), environment)
        charIndex += newCharIndex

        const lastLine = funcResults.slice(-1)[0]

        if (funcResults.length > 1)
          console.warn(`Function call "${name}" had more than one result!`
                    + ' (Using last result.)')
        if (!lastLine) console.warn(`Function "${name}" returned nothing!`)

        result += lastLine.command

        // console.groupEnd()

        continue
      }

      result += char
    }

    console.log('RESULT:', result)

    return result
  }

  processFunctionCall(code, environment) {
    // PROCESS PROCESS PROCESS

    // Getting name.
    let name = ''

    let char = ''
    let charIndex = -1
    while (true) {
      charIndex++
      char = code[charIndex]
      if (charIndex >= code.length) break

      if (char === '(') break

      name += char
    }

    let func
    console.log(environment.vars)
    if (environment.vars.hasOwnProperty(name)) {
      func = environment.vars[name]
      console.log('lel')
    } else {
      func = this.functions[name]
    }
    console.log('hi:', environment)
    console.log('fn:', func)
    const params = func.params
    const codeLines = func.codeLines
    const env = {vars: {}}

    // Getting arguments.
    const argsSliceStart = charIndex + 1
    let parenWeight = 0
    let currentArg = ''
    const args = []
    while (true) {
      charIndex++
      char = code[charIndex]
      if (charIndex >= code.length) break
      if (char === ')') {
        if (parenWeight === 0) {
          if (currentArg) {
            args.push(currentArg)
          }
          break
        } else {
          parenWeight--
        }
      }
      if (char === '(') {
        parenWeight++
      }
      if (char === ',' && parenWeight === 0) {
        args.push(currentArg)
        currentArg = ''
        continue
      }
      if (char === ' ' && currentArg == '') continue
      currentArg += char
    }
    const argCode = code.slice(argsSliceStart, charIndex)
    // console.log('Function name:', name)
    // console.log('Arguments:', args)

    console.log('test', environment.passedCode)
    for (let argIndex = 0; argIndex < params.length; argIndex++) {
      console.log('Param/arg', params[argIndex], '=', args[argIndex])

      if (args[argIndex]) {
        env.vars[params[argIndex]] = this.expression(
          args[argIndex], environment)
      }
    }

    if (environment.passedCode) {
      console.log('yay')
      env.vars[params[params.length - 1]] = {
        codeLines: environment.passedCode,
        params: []
      }
    }

    const funcResults = this.compile(codeLines.join('\n'), env)
    return {newCharIndex: charIndex + 1, funcResults, name}
  }

  handleLabels(stack) {
    // postprocessing is s c a r y

    const results = []

    let blockIndex = -1
    let block
    while (true) {
      blockIndex++
      block = stack[blockIndex]
      if (blockIndex >= stack.length) break

      if (!block.command) {
        results.push(block)
        continue
      }

      let newCommand = ''
      let charIndex = -1
      let char
      while (true) {
        charIndex++
        char = block.command[charIndex]
        if (charIndex >= block.command.length) break

        if (char === '@') {
          let labelName = ''
          while (true) {
            charIndex++
            char = block.command[charIndex]
            if (char === ' ') break
            if (charIndex > block.command.length) break
            labelName += char
          }
          const pos = `~ ~${this.labels[labelName] - blockIndex} ~`
          newCommand += pos + ' '
          continue
        }

        newCommand += char
      }

      results.push(Object.assign({}, block, {command: newCommand}))
    }

    return results
  }
}

const p = new Program()
let stack
stack = p.compile(`

define kar(x)
  say before
  !x()
  say after

!kar():
  say foo

`)
stack = p.handleLabels(stack)
console.dir(stack)
console.log(CBU.summonStack(stack))
<commit_msg>Note to self - this program doesn't work<commit_after>const groupFn = function(fn, label) {
  console.group(label || 'Group-function')
  const ret = fn()
  console.groupEnd()
  return ret
}

class Program {
  constructor() {
    this.functions = {}
    this.labels = {}
    this.defaultAttributes = {
      type: 'c', auto: true, conditional: false
    }
  }

  parseAttributes(str) {
    const timesAppearing = {}
    const validAttributes = [
      'c', 'i', 'r',
      '0', '1',
      '!', '?'
    ]
    const attributes = {}
    let contradictory
    let overallContradictory = 0
    const result = {}

    for (let char of str) {
      timesAppearing[char] = (timesAppearing[char] || 0) + 1
      if (timesAppearing[char] > 1) throw new Error(
        `In attributes "${str}" ${char} appears more than once`)

      if (!validAttributes.includes(char)) throw new Error(
        `In attributes "${str}" ${char} is an invalid attribute`)

      attributes[char] = true
    }

    contradictory = 0
    if (attributes['c']) {
      contradictory++
      result.type = 'c'
    }
    if (attributes['i']) {
      contradictory++
      result.type = 'i'
    }
    if (attributes['r']) {
      contradictory++
      result.type = 'r'
    }
    overallContradictory |= contradictory > 1

    contradictory = 0
    if (attributes['0']) {
      contradictory++
      result.auto = false
    }
    if (attributes['1']) {
      contradictory++
      result.auto = true
    }
    overallContradictory |= contradictory > 1

    contradictory = 0
    if (attributes['?']) {
      result.conditional = true
      contradictory++
    }
    if (attributes['!']) {
      result.conditional = false
      contradictory++
    }
    overallContradictory |= contradictory > 1

    if (overallContradictory) throw new Error(
      `Attributes "${str}" is contradictory`)

    const withDefaults = Object.assign({}, this.defaultAttributes, result)

    return withDefaults
  }

  compile(code, environment = {vars: {}}) {
    const lines = code.split('\n')
    const results = []

    LINE_LOOP:
    for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
      let line = lines[lineIndex]

      if (line === '')
        continue

      if (line.startsWith('define')) {
        // Getting name
        let name = ''

        let defCharIndex = 6
        while (true) {
          defCharIndex++
          const char = line[defCharIndex]

          if (defCharIndex >= line.length)
            break

          if (char === '(')
            break

          name += char
        }

        // Getting parameters
        let params = []
        let currentParam = ''

        while (true) {
          defCharIndex++
          const char = line[defCharIndex]

          if (defCharIndex >= line.length)
            break

          if (char === ')') {
            if (currentParam) {
              params.push(currentParam)
            }
            break
          }

          if (char === ',') {
            params.push(currentParam)
            currentParam = ''
            continue
          }

          if (char === ' ' && currentParam === '')
            continue

          currentParam += char
        }

        // Getting code lines
        const codeLines = []

        while (true) {
          lineIndex++
          line = lines[lineIndex]

          if (lineIndex > lines.length)
            break

          if (!line.startsWith('  '))
            break

          codeLines.push(line.slice(2))
        }

        // Storing function
        this.functions[name] = {codeLines, params}

        continue
      }

      if (line.startsWith('!')) {
        const env = Object.assign({}, environment)

        if (line.endsWith(':')) {
          const argCodeLines = []
          while (true) {
            lineIndex++
            const line = lines[lineIndex]
            if (lineIndex >= lines.length) break
            if (!line.startsWith('  ')) break
            argCodeLines.push(line.slice(2))
          }
          env.passedCode = argCodeLines
        }

        console.log('line:', line)

        const { funcResults, name } = this.processFunctionCall(
          line.slice(1), env)

        if (funcResults.length === 0) {
          console.warn(`Procedure call "${name}" had no results!`)
        }

        for (let r of funcResults) {
          results.push(r)
        }

        continue
      }

      if (line.startsWith('#')) {
        const blockName = line.slice(1)
        results.push({block: blockName})
        continue
      }

      if (line.startsWith('@')) {
        const labelName = line.slice(1)
        this.labels[labelName] = results.length
        continue
      }

      let attributeStr = ''
      let charIndex = -1
      let char = ''
      while (true) {
        charIndex++
        char = line[charIndex]
        if (char === ' ') {
          attributeStr = ''
          break
        }
        if (charIndex >= line.length) {
          attributeStr = ''
          break
        }
        if (char === ':') break
        attributeStr += char
      }

      let commandPart
      if (attributeStr) {
        let char = ''
        do {
          charIndex++
          char = line[charIndex]
        } while (char === ' ')
        commandPart = line.slice(charIndex)
      } else {
        commandPart = line
      }
      const attributes = this.parseAttributes(attributeStr)
      console.log('attributes proper:', attributes)

      const command = this.expression(commandPart, environment)

      const obj = Object.assign({command}, attributes)

      results.push(obj)
    }

    return results
  }

  expression(code, environment = {vars: {}}) {
    // TODO: put reused stuff in here because having identical code in multiple
    // parts of a program is BAAAD!

    // Parts of lines that should be put in here:
    // * everything past the command name part of code lines (past first space)
    //   (or just the whole command line)
    // * arguments (each in a separate expression call)

    let charIndex = -1
    let result = ''

    console.log('EXPRESSION:', code)

    while (true) {
      charIndex++
      let char = code[charIndex]
      if (charIndex >= code.length) break

      // Variables
      if (char === '$') {
        let name = ''
        while (true) {
          charIndex++
          char = code[charIndex]
          if (charIndex >= code.length) break

          if (char === ' ') {
            charIndex--
            break
          }

          name += char
        }

        // console.log('Variable:', name)
        // console.log('Environment:', environment)
        // console.log('Value:', environment.vars[name])

        if (!environment.vars.hasOwnProperty(name))
          throw new Error(`Access to undefined variable: "${name}"`)

        result += environment.vars[name]

        continue
      }

      // Function calls
      if (char === '^') {
        // console.group('fn call')

        const { funcResults, newCharIndex, name } = this.processFunctionCall(
          code.slice(charIndex + 1), environment)
        charIndex += newCharIndex

        const lastLine = funcResults.slice(-1)[0]

        if (funcResults.length > 1)
          console.warn(`Function call "${name}" had more than one result!`
                    + ' (Using last result.)')
        if (!lastLine) console.warn(`Function "${name}" returned nothing!`)

        result += lastLine.command

        // console.groupEnd()

        continue
      }

      result += char
    }

    console.log('RESULT:', result)

    return result
  }

  processFunctionCall(code, environment) {
    // PROCESS PROCESS PROCESS

    // Getting name.
    let name = ''

    let char = ''
    let charIndex = -1
    while (true) {
      charIndex++
      char = code[charIndex]
      if (charIndex >= code.length) break

      if (char === '(') break

      name += char
    }

    let func
    console.log(environment.vars)
    if (environment.vars.hasOwnProperty(name)) {
      func = environment.vars[name]
      console.log('lel')
    } else {
      func = this.functions[name]
    }
    console.log('hi:', environment)
    console.log('fn:', func)
    const params = func.params
    const codeLines = func.codeLines
    const env = {vars: {}}

    // Getting arguments.
    const argsSliceStart = charIndex + 1
    let parenWeight = 0
    let currentArg = ''
    const args = []
    while (true) {
      charIndex++
      char = code[charIndex]
      if (charIndex >= code.length) break
      if (char === ')') {
        if (parenWeight === 0) {
          if (currentArg) {
            args.push(currentArg)
          }
          break
        } else {
          parenWeight--
        }
      }
      if (char === '(') {
        parenWeight++
      }
      if (char === ',' && parenWeight === 0) {
        args.push(currentArg)
        currentArg = ''
        continue
      }
      if (char === ' ' && currentArg == '') continue
      currentArg += char
    }
    const argCode = code.slice(argsSliceStart, charIndex)
    // console.log('Function name:', name)
    // console.log('Arguments:', args)

    console.log('test', environment.passedCode)
    for (let argIndex = 0; argIndex < params.length; argIndex++) {
      console.log('Param/arg', params[argIndex], '=', args[argIndex])

      if (args[argIndex]) {
        env.vars[params[argIndex]] = this.expression(
          args[argIndex], environment)
      }
    }

    if (environment.passedCode) {
      env.vars[params[params.length - 1]] = {
        codeLines: environment.passedCode,
        params: []
      }
    }

    const funcResults = this.compile(codeLines.join('\n'), env)
    return {newCharIndex: charIndex + 1, funcResults, name}
  }

  handleLabels(stack) {
    // postprocessing is s c a r y

    const results = []

    let blockIndex = -1
    let block
    while (true) {
      blockIndex++
      block = stack[blockIndex]
      if (blockIndex >= stack.length) break

      if (!block.command) {
        results.push(block)
        continue
      }

      let newCommand = ''
      let charIndex = -1
      let char
      while (true) {
        charIndex++
        char = block.command[charIndex]
        if (charIndex >= block.command.length) break

        if (char === '@') {
          let labelName = ''
          while (true) {
            charIndex++
            char = block.command[charIndex]
            if (char === ' ') break
            if (charIndex > block.command.length) break
            labelName += char
          }
          const pos = `~ ~${this.labels[labelName] - blockIndex} ~`
          newCommand += pos + ' '
          continue
        }

        newCommand += char
      }

      results.push(Object.assign({}, block, {command: newCommand}))
    }

    return results
  }
}

const p = new Program()
let stack
stack = p.compile(`

define loop(times, main)
  scoreboard players set LOOP loopCounter $times
  setblock ~ ~2 ~ redstone_block
  #glass
  #quartz_ore
  i0: scoreboard players remove LOOP loopCounter 1
  scoreboard players test loopCounter LOOP 0 0
  ?: setblock @done redstone_block
  scoreboard players test loopCounter LOOP 1 *
  ?: setblock @body redstone_block
  #glass
  @body
  #quartz_ore
  i0: say Loop
  !main()
  setblock @done redstone_block
  #glass
  @done
  #quartz_ore
  i0: say Done
  #glass

i0:
!loop(5):
  say foo

`)
stack = p.handleLabels(stack)
console.dir(stack)
console.log(CBU.summonStack(stack))
<|endoftext|>